Java – NullPointerException at the end of the file

What I want is to access the EOF by reading the command line from the console and typing Ctrl z from the BufferedReader The following code does this The problem is that it issues a NullPointerException after reaching EOF Is there any way to skip this exception? Or rather, what is the correct way to achieve EOF by reading BufferedReader from the 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) {} 
    }

}

Solution

At present, you actually detect the characters' ^ 'and' Z ', which is not really a control character like' ^ '

The exception you get is actually a hint of how you should deal with it From BufferedReader ReadLine documentation:

So basically you should loop until readLine returns null

String line;
while((line = read.readLine()) != null)
{
    // Do something with line
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>