2

I have a particular method where I want to count the number of lines in a text file and then read the file what I am doing is counting the number of lines in the file by iterating over the read.nextLine() and then resetting the buffer and reading from the start of the file again. I am not sure what I am doing wrong

public void ReadFile() throws IOException{
 try{
    FileReader fr = new FileReader(path);
    BufferedReader read = new BufferedReader(fr);
    int numberOfLines=0;
    while(read.readLine()!= null)
    {
        numberOfLines++;  // Getting the number of lines


    }

    read.reset();
    System.out.println(numberOfLines + ": is the no of lines");
    baseString.append(read.readLine());
    baseString.append(read.readLine());
    baseString.append(read.readLine());
    System.out.println(baseString);
 }
 catch(IOException e){
        e.printStackTrace();
 }
}

base string is just a Stringbuffer

private StringBuffer baseString = new StringBuffer();

I explicitly need the count to perform some operation

user1801279
  • 1,507
  • 5
  • 22
  • 38

2 Answers2

2

As mentioned here the file is read sequentially by BufferedReader, so you can't go back to the beginning of file with reset of BufferedReader

You have to create new FileReader and BufferedReader

OR

use RandomAccessFile

Community
  • 1
  • 1
Anirudha
  • 30,881
  • 7
  • 64
  • 81
1

You need to call mark() on the stream. Reader.reset() isn't guaranteed to work if the stream hasn't been previously marked. The BufferedReader implementation of reset() in particular is only documented as returning to the previous mark.

Kenster
  • 18,710
  • 21
  • 68
  • 90
  • that would not work..take a look at [this](http://stackoverflow.com/questions/262618/java-bufferedreader-back-to-the-top-of-a-text-file) – Anirudha Apr 09 '13 at 18:38