繁体   English   中英

如何将inputstream记录到android中的文件然后解析

[英]How to log inputstream to file in android and then parse it

我从HttpUrlConnection(connection.getInputStream())接收InputStream,并使用DocumentBuilder(documenbtBuilder.parse(inputStream))解析输入流。 解析之前,我想将接收到的数据写入日志文件。 当我这样做时,我得到org.xml.sax.SAXParseException:parse方法中文档Exception的意外结尾。 如果我不写文件,我的代码可以正常工作,但是我需要记录接收到的数据。

请在下面找到写入文件的代码:

  final InputStream input = connection.getInputStream();

    writeLogInfo(input);

    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

    //Method that writes tito log file.

    private void writeLogInfo(InputStream input){

     OutputStream os = new FileOutputStream("mylogfile.txt");

     byte[] buffer = new byte[1024];

     int byteRead;

     while((byteRead = input.read(buffer)) != -1){
        os.write(buffer,0,byteRead);
     }

     os.flush();

     os.close();

   }

我怀疑这是由于InputStream的多次使用,因为代码在我不调用writeLogInfo()时有效。 我没有在代码中的任何地方关闭输入流。 我在这里做错了什么?

将内容写入文件时,您将到达输入流的末尾。

因此,在此之后,当您尝试解析时,您将获得异常。

您需要在输入流上使用markreset方法,然后再将其传递给documentbuilder。

另外,首先,您需要检查输入流是否支持mark。

这是javadoc,供您参考

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

您确定文件大小小于1024字节。 如果不是,为什么不将“ inputstream”放入BufferredInputstream,然后创建字节数组。

BufferedInputStream bin= new BufferedInputStream(new DataInputStream(input));
byte[] buffer= new byte[bin.available()];
bin.read(buffer);
os.write(buffer);
......
......
bin.close();
......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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