简体   繁体   中英

How to log and parse InputStream in Android

I parse an InputStream with following code and it works fine.

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XmlHandlerMatchDetails handler = new XmlHandlerDetails();
xr.setContentHandler(handler);
xr.parse(new InputSource(data));

Now I need to log the InputStream to check it, I change the previous code in this way:

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XmlHandlerMatchDetails handler = new XmlHandlerDetails();
xr.setContentHandler(handler);
xr.parse(new InputSource(data));

BufferedReader br = new BufferedReader(new InputStreamReader(data)); 
StringBuilder sb = new StringBuilder(); 
String line; 
while ((line = br.readLine()) != null) {     
   sb.append(line); 
} 
String text = sb.toString();
Log.i(mTag, text);

But I have the error

09-19 12:13:02.982: ERROR/MyClass(338): java.io.IOException: Attempted read on closed stream.

How it's possible to log or to convert the stream to string without close it?

EDIT - SOLVED!!!

I solve it parsing the string instead of InputStream

xr.parse(new InputSource(new StringReader(text)));

I'm not sure this is the problem, but you could try re-writing your while loop to this:

while( br.ready() )
  sb.append( br.readLine() );

Another thing that pops to my mind, is that the InputStream you use (data), might not be able to be read twice - thus parsing it with the XmlReader first causes it to close and then it will not be open when you try to parse it with the BufferedReader. To verify this, try to run the BufferedReader without first parsing the data with the XmlReader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM