10

What I wanted is to reach EOF by typing Ctrl + z from command line with BufferedReader reading from console. The following code does so. But the problem is, it issues a NullPointerException after reaching EOF. Is there a way to skip this exception? Or more precisely, what is the proper way of reaching EOF with BufferedReader reading from console?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class EOF {

    public static void main(String args[]) {
        String s = "";
        String EOF = "^z";
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        try {
            while (!s.equals(EOF)) {
                s = read.readLine();   
            }
        } catch (IOException e) {} 
    }

}
starsplusplus
  • 1,232
  • 3
  • 19
  • 32
Tahmid Ali
  • 805
  • 9
  • 29

4 Answers4

12

Or more precisely, what is the proper way of reaching EOF with bufferedReader reading from console?

Currently you're actually detecting the characters '^' and 'z' it's not like '^' is really a control character.

The exception you're getting is actually a hint as to how you should be handling this. From the docs for BufferedReader.readLine:

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So basically you should loop until readLine returns null.

String line;
while((line = read.readLine()) != null)
{
    // Do something with line
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

See how much a debugger can help:

enter image description here

After I press ctrl + z, s has null value, hence you're getting this exception, since it's like writing !null.equals(EOF).

Why?

Because BufferedReader#readLine returns "null if the end of the stream has been reached".

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

Just use null as EOF signal.

    while((s=read.readLine())!= null)
    {
        .....
    }
Agustí Sánchez
  • 10,455
  • 2
  • 34
  • 25
0
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

String str;
while((str=input.readLine()) != null ) {
    // 
}
Sorter
  • 9,704
  • 6
  • 64
  • 74