Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a BufferedReader more than once in Java

I have the following piece of code in Java:

HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
con.connect();
InputStream stream = con.getInputStream();
BufferedReader file = new BufferedReader(new InputStreamReader(stream));

At this point, I read the file from start to end while searching for something:

while (true)
{
    String line = file.readLine();
    if (line == null)
        break;
    // Search for something...
}

Now I want to search for something else within the file, without opening another URL connection.

For reasons unrelated to this question, I wish to avoid searching for both things "in a single file-sweep".

Questions:

  1. Can I rewind the file with reset?

  2. If yes, should I apply it on the InputStream object, on the BufferedReader object or on both?

  3. If no, then should I simply close the file and reopen it?

  4. If yes, should I apply it on the InputStream object, on the BufferedReader object or on both?

  5. If no, how else can I sweep the file again, without reading through the URL connection again?

like image 701
barak manos Avatar asked Oct 02 '22 19:10

barak manos


1 Answers

You can rewind the file with reset(), provided that you have mark()'ed the position you want to rewind to. These methods should be invoked on the decorator, i.e. BufferedReader.

However, you may probably want to reconsider your design as you can easily read the whole file into some data structure (even a list of strings, or some stream backed by a string) and use the data multiple times.

like image 197
gd1 Avatar answered Oct 05 '22 13:10

gd1