NullPointerException从文件读取行

时间:2015-10-07 19:25:27

标签: java

我有这段代码:

public static void main(String[] args) {
    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader("hello.txt"));

        String line;

        while ((line = br.readLine().trim()) != null) {
            if (line.startsWith("Hello")) {
                line = br.readLine().trim();
            } else {
                ... code ...
            }
        }

        br.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但是一旦文件到达结尾,我就会收到此错误:

  

线程中的异常" main"显示java.lang.NullPointerException

在线:

while ((line = br.readLine().trim()) != null) {

为什么呢?如何解决?

3 个答案:

答案 0 :(得分:2)

尝试以下方法;你试图读取的ine是null因此调用trim会抛出NPE;

while (br.readLine() != null)
        {
            line = br.readLine().trim()
        }

答案 1 :(得分:0)

当您尝试使用readLine()

进行阅读时
line = br.readLine().trim())

如果br.readLine()返回 null ,则调用trim()会导致NPE。

while ((line = br.readLine()) != null) {
    line.trim();                   
    if (line.startsWith("Hello")) {
        if ((line = br.readLine()) != null) {
            line.trim();
        }

    } else {

    }
}

答案 2 :(得分:0)

while ((line = br.readLine().trim()) != null)

删除trim() 并在while循环中添加它。

line = line.trim();