开发者

How to log and parse InputStream in Android

开发者 https://www.devze.com 2023-04-06 08:56 出处:网络
I parse an InputStream with following code and it works fine. SAXParserFactory spf = SAXParserFactory.newInstance();

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开发者_C百科 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号