randeepsp
randeepsp

Reputation: 3852

how to make a buffered reader read from the beginning instead of using another object

In the below written code, i want the second while loop to read from the second line of the same file which the first while loop is using. As of the now the second while loop is reading from the third line of the file. I can do it by using another buffered reader. but is there another better way ?

filename = data1
readFile = new File(filename);
BufferedReader reader = null;
try
{
    reader = new BufferedReader( new FileReader(readFile) );
}
catch (IOException ioe)
{
    System.err.println("Error: " + e.getMessage());     
}
String newline;
int secondRecord = 0;
while((secondRecord < 2) && ((newline = readline(reader)) != null))
    {
    System.out.println(newline);
            secondRecord ++;
    }

while ((newline = readline(reader)) != null)
    {
    System.out.println(newline);
    }

Upvotes: 0

Views: 3004

Answers (4)

randeepsp
randeepsp

Reputation: 3852

I should have used a do while loop instead of the second while. That way it would read the second line as well.

Upvotes: 0

rsp
rsp

Reputation: 23373

You can place a mark at the point where you want to return later. (Asuming your use of the file won't require a readahead bufer that is too big.)

Upvotes: 0

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

BufferedReader supports mark() and reset(). Thus you should call mark() before your first loop, and reset() after it, and it then should be able to read the same lines again.

Of course, only do this if the file is not too big, since the BufferedReader has to keep everything in memory to do this.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533820

I would read the file into a List and process the list how you want.

List<String> lines = FileUtils.readLines(readFile);
for(String line: lines.subList(0,2))
    System.out.println("first loop "+line);
for(String line: lines.subList(2, lines.size()))
    System.out.println("second loop "+line);

Upvotes: 0

Related Questions