【问题标题】:How to log inputstream to file in android and then parse it如何将输入流记录到android中的文件然后解析它
【发布时间】:2014-06-25 22:20:09
【问题描述】:

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

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

  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() 时代码有效。我没有在我的代码中的任何地方关闭输入流。我在这里做错了什么?

【问题讨论】:

  • 确实,您不能像那样双重使用 InputStream。您基本上有三个选择:1)两次获取数据 2)将数据写入文件,然后打开 FileInputStream 并将其读回以进行解析。 3)创建自己的实现 InputStream 的包装类,将其包装在源类周围,以便它的 read() 调用源 read() 并在将结果数据提供给解析器之前记录结果数据,解析器作为最终消费者将控制节奏阅读。

标签: java android


【解决方案1】:

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

所以在那之后,当你尝试解析时,你会得到异常。

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

另外,首先你需要检查输入流是否支持标记。

这里是javadoc,供你参考

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

【讨论】:

  • 如果来自网络的 InputStream 支持倒带,我会有点惊讶。
【解决方案2】:

您确定文件的大小小于 1024 字节吗?如果不是,为什么不将“输入流”放入 BufferredInputstream,并创建字节数组..

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

【讨论】:

  • 它可能不小于缓冲区大小是在while循环中执行读写操作的原因 - 但这与问题无关。
  • @kaze。我试过你的方法,但文件是空的。我无法关闭输入流 (bin.close()),因为我再次使用它来解析它。我还记录了缓冲区的长度。它不是空的。所以 bin 包含数据但文件是空的。
  • @kaze。没有。解析时不会重置输入流。它抛出文档异常的意外结束。我尝试在解析时使用 new InputSource(connection.getInputStream()) 获取数据,但这也不起作用。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 2012-06-07
  • 2012-06-13
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
相关资源
最近更新 更多