如何解决:java.io.IOException:Stream关闭

时间:2015-05-18 03:17:44

标签: java

这是一个以流方式解析JSON结构的程序。 现在是晚上10点,我的大脑很累,这就是为什么我似乎无法弄清楚为什么我会得到异常:    java.io.Exception:Stream关闭。

如果这里的专家可以帮助我摆脱这个例外,我将非常感谢帮助我解决这个问题。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;

import java.util.Properties;

public class JacksonStreaming {

    public static void main(String[] args) {
        System.out.println("Entered Main");
        try {
            new JacksonStreaming().getNames();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

ObjectMapper jsonMapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory();

Properties prop = new Properties();
String filePath = "";
final String[] path = new String[] {"myReport", "docReports", "part1/.", "myAnalysis", "matches", "name"};

void getNames()  {
    System.out.println("Entered getNames"); 
    //final String resourceName = "C:/Users/Ilango/ellyworkspace/JacksonStreamingFindData/src/jsonFormattedModified.json";
    JsonNode rootNode;


            try {
                //InputStream in = getClass().getClassLoader().getResourceAsStream("config.properties");
                BufferedReader fileReader = new BufferedReader(new FileReader("C:/Users/Ilango/ellyworkspace/JacksonStreamingFindData/src/jsonFormattedModified.json"));
                System.out.println("fileReader is: " + fileReader); 
                rootNode = jsonMapper.readTree(fileReader);
                System.out.println("Return value of jsonMapper.readTree is: " +rootNode);
                findByPath(rootNode);
                JsonParser jsonParser = jsonFactory.createParser(fileReader);
                System.out.println("JsonParser is: " + jsonParser);

                int pathIndex = 0;
                List<String> names = new ArrayList<String>();
                boolean breakOnClose = false;


                //try {
                    //try {
                        while (jsonParser.nextToken() != null) {
                            final String fieldName = jsonParser.getCurrentName();
                            if (fieldName == null) {
                                continue;
                            }
                            if (breakOnClose && fieldName.equals(path[path.length - 2])) {
                                System.out.println("Stopping search at end of node " + fieldName);
                                break;
                            }
                            if (jsonParser.getCurrentToken() != JsonToken.FIELD_NAME) {
                                continue;
                            }
                            // System.out.println("Field " + fieldName);
                            if (pathIndex >= path.length - 1) {
                                if (fieldName.equals(path[path.length - 1])) {
                                    // move from field name to field value.
                                    try {
                                        jsonParser.nextToken();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } 
                                    String name;
                                    //try {
                                        name = jsonParser.getValueAsString();
                                    //} catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        //e.printStackTrace();
                                    //}
                                    if (name == null) {
                                        throw new RuntimeException("No value exists for field " + fieldName);
                                    }
                                    names.add(name);
                                    System.out.println("Found " + fieldName + " value: " + name);
                                }
                            } else if (fieldName.equals(path[pathIndex])) {
                                System.out.println("Found node " + path[pathIndex]);
                                pathIndex++;
                                if (pathIndex >= path.length - 1) {
                                    System.out.println("Looking for names ...");
                                    breakOnClose = true;
                                    // prevent breaking on "matches" value json-token.
                                    try {
                                        jsonParser.nextFieldName();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } 
                                }
                            }
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 

            } 






            void findByPath(JsonNode jn) {
                System.out.println("Entered findByPath");   
                JsonNode matchesNamesNode = jn;
                for (int i = 0; i < path.length - 1; i++) {
                    matchesNamesNode = matchesNamesNode.path(path[i]);
                }
                if (matchesNamesNode.isMissingNode()) {
                    throw new RuntimeException("No node with names found.");
                }
                System.out.println("Tree names: " + matchesNamesNode.findValuesAsText("name"));
            }


     }// end of class JacksonStreaming
      def setCount(count: Int) {
        this.count = count
      }
    }

堆栈跟踪:

Entered Main
Entered getNames
fileReader is: java.io.BufferedReader@33e5ccce
Return value of jsonMapper.readTree is: {"type":"ImportantIncidentInfo","incidentTimestamp":"2014-05-15T10:09:27.989-05:00","numOfMatches":4,"myReport":{"docReports":{"part1/.":{"path":["unknown"],"myAnalysis":{"matches":[{"id":{"major":1,"minor":0},"name":"US SSN","position":13,"string":" 636-12-4567 "},{"id":{"major":3,"minor":0},"name":"MasterCard Credit Card Number","position":35,"string":" 5424-1813-6924-3685 "}]},"cleanedUpData":[{"startPosition":0,"endPosition":65,"frameContent":""}],"minedMetadata":{"Content-Encoding":"ISO-8859-1","Content-Type":"text/html; charset=iso-8859-1"},"deducedMetadata":{"Content-Type":"text/html; iso-8859-1"}},"part2/.":{"path":["unknown"],"myAnalysis":{"matches":[{"id":{"major":1,"minor":0},"name":"SSN","position":3,"string":" 636-12-4567\r"},{"id":{"major":3,"minor":0},"name":"MasterCard Credit Card Number","position":18,"string":"\n5424-1813-6924-3685\r"}]},"cleanedUpData":[{"startPosition":0,"endPosition":44,"frameContent":""}],"minedMetadata":{"Content-Encoding":"windows-1252","Content-Type":"text/plain; charset=windows-1252"},"deducedMetadata":{"Content-Type":"text/plain; iso-8859-1"}}}},"whatSetItOffEntry":{"action":"Log","component":{"type":"aComponent","components":[{"type":"PatternComponent","patterns":[1],"not":false}],"not":false},"ticketInfo":{"createIncident":true,"tags":[],"seeRestrictedIds":[{"type":"userGroup","name":"SiteMasters","description":"Group for SiteMasters","masters":["04fb02a2bc0fba"],"members":[],"id":"04fade"}]},"letmeknowInfo":{"createNotification":true,"contactNames":["someguy@gmail.com"]}},"seeRestrictedIds":["04fade66c0"],"status":"New","timeStamps":["2015-05-15T10:09:27.989-05:00"],"count":1}
Entered findByPath
Tree names: [US SSN, MasterCard Credit Card Number]
JsonParser is: com.fasterxml.jackson.core.json.ReaderBasedJsonParser@23223dd8
java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
    at java.io.BufferedReader.read(BufferedReader.java:278)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.loadMore(ReaderBasedJsonParser.java:153)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipWSOrEnd(ReaderBasedJsonParser.java:1855)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:571)
    at com.myorg.myapi.JacksonStreaming.getNames(JacksonStreaming.java:55)
    at com.myorg.myapi.JacksonStreaming.main(JacksonStreaming.java:19)

1 个答案:

答案 0 :(得分:8)

您的代码出现了问题(请参阅注释):

// you create a BufferedReader (no problems per se)
BufferedReader fileReader = new BufferedReader(new FileReader("C:/Users/Ilango/ellyworkspace/JacksonStreamingFindData/src/jsonFormattedModified.json"));

 // this consumes the fileReader stream
rootNode = jsonMapper.readTree(fileReader);

findByPath(rootNode);

// the next line is where the problem is happening
// fileReader has already been consumed, so the call to createParser() must fail
JsonParser jsonParser = jsonFactory.createParser(fileReader); // java.io.IOException: Stream closed

您的问题的解决方案是制作流的副本,或者在已经读取之后不再使用它。