0

i have to count the lines on a file but later in the code I also have to print what's in that file, but I can't use the reader twice it just says null. How can I work this out without creating a bunch of bufferedreader objects? thanks

David Benalal
  • 105
  • 1
  • 2
  • 7
  • 2
    just close the stream and create a new object, possible duplicate of http://stackoverflow.com/questions/5421653/reset-buffer-with-bufferedreader-in-java and http://stackoverflow.com/questions/262618/java-bufferedreader-back-to-the-top-of-a-text-file – riteshtch Mar 06 '16 at 19:53
  • count the number of lines you print instead.? – DMO-NZ Mar 06 '16 at 19:54
  • When you say 'later in the code' do you mean in the same method? You can always have a counter for the number of lines and print the lines. – Rahul Sharma Mar 06 '16 at 20:00

3 Answers3

0
  1. Print and count at the same time?
  2. Move the lines to an array then print them?
  3. Make sure you've closed the file before reopening again?
Mark Sheekey
  • 608
  • 7
  • 23
0

Try closing the buffer, and then re-opening it again.

    BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
    String line = bufferedReader.readLine();
    int lineCount = 0;
    while(line != null){
        lineCount += 1;
        line = bufferedReader.readLine();
    }
    System.out.println("Line count is: " + lineCount);

    bufferedReader.close();
    bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));

    line = bufferedReader.readLine();
    while(line != null){
        System.out.println(line);
        line = bufferedReader.readLine();
    }
}
W. Lee
  • 105
  • 5
-1

You can use BufferedReader's mark() and reset() methods to jump back to a specific position.

try (BufferedReader r = new BufferedReader(new FileReader("somefile.txt"))) {
    // marks this position for the next 10 characters read
    // after that the mark is lost
    r.mark(10);

    // do some reading

    // jump back to the mark
    r.reset();
}

Note that, BufferedReader supports marking but not all Readers do. You can use markSupported() to check.

nyname00
  • 2,496
  • 2
  • 22
  • 25