简体   繁体   English

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

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

I am receiving an InputStream from HttpUrlConnection (connection.getInputStream()), and I am parsing the input stream using DocumentBuilder (documenbtBuilder.parse(inputStream)). 我从HttpUrlConnection(connection.getInputStream())接收InputStream,并使用DocumentBuilder(documenbtBuilder.parse(inputStream))解析输入流。 Before parsing, I want to write the received data to log file. 解析之前,我想将接收到的数据写入日志文件。 When I do that, I get org.xml.sax.SAXParseException: Unexpected end of document Exception in the parse method. 当我这样做时,我得到org.xml.sax.SAXParseException:parse方法中文档Exception的意外结尾。 My code works fine if I don't write to file, but I need to log the data received. 如果我不写文件,我的代码可以正常工作,但是我需要记录接收到的数据。

Please find the code that writes to file below : 请在下面找到写入文件的代码:

  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();

   }

I suspect it is because of multiple use of InputStream, since the code works when I don't invode writeLogInfo(). 我怀疑这是由于InputStream的多次使用,因为代码在我不调用writeLogInfo()时有效。 I am not closing the inputstream anywhere in my code. 我没有在代码中的任何地方关闭输入流。 What am I doing wrong here ? 我在这里做错了什么?

When you are writing the content to a file, you are reaching the end of the inputstream. 将内容写入文件时,您将到达输入流的末尾。

So after that, when you are trying to parse, you get the exception. 因此,在此之后,当您尝试解析时,您将获得异常。

You need to use mark and reset methods on the inputstream before passing it to documentbuilder. 您需要在输入流上使用markreset方法,然后再将其传递给documentbuilder。

Also, first you need to check if the input stream supports mark. 另外,首先,您需要检查输入流是否支持mark。

Here is the javadoc, for your reference 这是javadoc,供您参考

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

Are you sure the size of the file is under 1024 bytes. 您确定文件大小小于1024字节。 If not why don't you put your "inputstream" to BufferredInputstream, and create the byte array.. 如果不是,为什么不将“ 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