-1

I have file called "a.txt" inside of which I have this data:

A
B
C
D

When I run this code, I get unexpected result:

BufferedReader bufferedReader = new BufferedReader (new FileReader ("a.txt"));
while (true) {
    System.out.println ("start");
    while (bufferedReader.readLine () != null) {
        System.out.println (bufferedReader.readLine ());
    }
    Thread.sleep (1000);
}

OUTPUT:

start
B
D
start
start
start
//keeps printing start

What I expected was of course:

start
A
B
C
D
start
start
//keeps printing start

Does anyone know what might be the problem? This honestly shocked me, as it looked easy when I first saw it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Stefan
  • 969
  • 6
  • 9

3 Answers3

2

For each (successful) iteration of the loop, you're reading two lines - one in the while condition, and then another one in the loop's body. The line read in the loop's condition is discarded, and thus you see the missing line.

Instead, you can store the line in a variable in the loop's condition, and then use it in the loop's body:

String line;
while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

bufferedReader.readLine () reads the next line and you're calling it twice

1

You are calling bufferedReader.readLine () twice whereas you are supposed to call it once. Do it as follows:

String line = bufferedReader.readLine();
while (line != null) {
    System.out.println(line);
    line = bufferedReader.readLine();
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110