Pawellp
Pawellp

Reputation: 1

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 ?

Upvotes: 0

Views: 618

Answers (3)

ReneS
ReneS

Reputation: 3545

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.

Upvotes: 1

Oni1
Oni1

Reputation: 1505

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
}

Upvotes: 0

dcsalmon
dcsalmon

Reputation: 61

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.

Upvotes: 0

Related Questions