Use the same getInputStream() for 2 different bufferedReader

Asked

Viewed 136 times

3

I need to access a file on an HTTP server and pull information from two different places inside that file. Right now I can take away just one. My doubt is, I can just do:

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(con.getInputStream()));

whereas

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

or I need to make a new HttpURLConnection for that reason?

  • 3

    Joper, welcome to [en.so]! You should not reuse Inputstream this way in no way. It may even work depending on how it is implemented, but this can lead to worse errors. For example, when a stream is closed the other will also be closed inadvertently. That being said, I cannot understand exactly what you are doing. Could you edit the question by putting an example of this file? You are reading the same file on two different websites or a file that contains two information?

1 answer

2

It makes no sense to create two BufferedReaders pointing to the same InputStream. In practice they will be working on the same thing. If you try to read a file using BufferedReader in and then try to read the same file using the BufferedReader in2, the in2 will continue where the in stopped.

That’s because classes like BufferedReader and InputStreamReader are only adding behavior to InputStream, but the object remains the same.

You need to create two InputStreams. Or you can in the same InputStream remove the two information you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.