简体   繁体   English

BufferedReader和InputStream错误读取

[英]BufferedReader and InputStream wrong read

I have a big problem with reading data from stream. 我从流中读取数据时遇到大问题。

I have code like this : 我有这样的代码:

 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 String topic = bufferedReader.readLine();

 while ((bytesRead = inputStream.read(array, 0, array.length)) != -1) {
            // do something with array of bytes
        }

Firstly, I want to get topic name , which is a single word ended with \\n. 首先,我要获取主题名称,即以\\ n结尾的单个单词。 Next, I want to read rest of the data ( I am reading this in chunks ). 接下来,我想读取其余数据(我正在分块读取)。

The problem is that inputStream.read return -1 because everything is read in bufferedReader. 问题是inputStream.read返回-1,因为所有内容都在bufferedReader中读取。 How can I fix it ? 我该如何解决?

Continue to use the bufferedreader and do not read data from the side/underneath. 继续使用bufferedreader,不要从侧面/下方读取数据。 The last reader is buffered hence it can read ahead and so the inputstream is empty. 最后一个读取器已缓冲,因此可以提前读取,因此输入流为空。

It is like a pipeline. 就像管道。 If you start to drill a hole into the middle of it, expect that there has already oil flown past that new hole, hence you cannot retrieve it by open the pipeline in the middle. 如果您开始在其中部钻一个孔,则应该已经有油流过该新孔,因此您无法通过打开中部的管道来取回它。

you need to read all of your data from the BufferedReader. 您需要从BufferedReader中读取所有数据。 After you wrap inputStream, you can't easily go back. 包装好inputStream之后,就无法轻松返回。 Alternatively, you can read the first line from inputStream by reading chars and checking for newline. 或者,您可以通过读取char并检查换行符来从inputStream中读取第一行。

You're instancing a object of BufferedReader with your InputStream, so the content of your InputStream is already "saved" in your BufferedReader! 您正在使用InputStream实例化BufferedReader的对象,因此InputStream的内容已“保存”在BufferedReader中! So continue reading of your BufferedReader object like this: 因此,像这样继续读取您的BufferedReader对象:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String topic = bufferedReader.readLine();

while ((bytesRead = bufferedReader.read(array, 0, array.length)) != -1) {
        // do something with array of bytes
}

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

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