文件结尾NullPointerException [英] End of file NullPointerException

查看:73
本文介绍了文件结尾NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是通过在命令行中输入<$ c $来达到 EOF ,方法是 Ctrl + z c> BufferedReader 从控制台读取。以下代码这样做。但是问题是,在达到 EOF 之后,它会发出 NullPointerException 。有没有办法跳过此异常?或者更确切地说,通过控制台读取 BufferedReader 达到 EOF 的正确方法是什么?

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) {} 
    }

}


推荐答案


或更准确地说,通过console.bufferedReader读取EOF的正确方法是什么?

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

当前,您实际上正在检测字符'^'和'z',而不是'^'确实是控制字符。

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

实际上,您得到的异常提示应该如何处理。从 BufferedReader.readLine的文档中

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


返回值:

包含以下内容的字符串行,不包括任何行终止符;如果已到达流的末尾,则返回null。

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

readLine 返回 null

String line;
while((line = read.readLine()) != null)
{
    // Do something with line
}

这篇关于文件结尾NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆