简体   繁体   中英

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. 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. How can I fix it ?

Continue to use the bufferedreader and do not read data from the side/underneath. 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. After you wrap inputStream, you can't easily go back. Alternatively, you can read the first line from inputStream by reading chars and checking for newline.

You're instancing a object of BufferedReader with your InputStream, so the content of your InputStream is already "saved" in your BufferedReader! So continue reading of your BufferedReader object like this:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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