无法在Java中修复Null指针异常

rye*_*ayo -2 java

我在这里看了这个问题,并按照答案.然而,编译器仍在抱怨空指针异常.这是关于编译器抱怨的代码块:

public class readLogger {
    DLQPush dlqPush = new DLQPush();
    public String values[];
    int condition = 2;
    public BufferedReader reader = null;

public void readFile() {
    try {
        reader = new BufferedReader(new FileReader(
                "/var/tmp/checkresults.log"));
    } catch (FileNotFoundException e) {
        System.err.println("ERROR: FILE NOT FOUND!\n");
    }
    String str = null;
    try {
        while ((str = reader.readLine()) != null) {
            if (str.trim().length() == 0) {
                continue;
            }
            values = str.split("\t");
            System.out.println(values[1] + values[2]);
            classifyStatus();

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器特别抱怨这一行:

while ((str = reader.readLine()) != null) {
Run Code Online (Sandbox Code Playgroud)

这是我的主要课程:

import java.io.IOException;
//import org.dcm4che3.tool.storescu.*;

public class Main {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) {

        readLogger rLog = new readLogger();
        rLog.readFile();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在前面的问题的链接中描述了必要的修复,但我的编译器仍在抱怨它:

ERROR: FILE NOT FOUND!

Exception in thread "main" java.lang.NullPointerException
    at readLogger.readFile(readLogger.java:25)
    at Main.main(Main.java:13)
Run Code Online (Sandbox Code Playgroud)

没关系错误,因为我已经将它导出到JAR文件并将其放在Linux中但它仍然在Linux中抛出NullPointer.有没有人对如何修复NullPointer异常有任何想法?

Men*_*ena 5

您的reader变量是在语句中null调用readLine时:while ((str = reader.readLine()) != null) {,因为找不到该文件(请参阅您自己的print语句).

因此,你抛出一个NullPointerException通过调用readLine一个null BufferedReader参考.

这里的最佳做法readFile是在找不到文件时停止执行方法.

作为替代方案,您可能希望在nullreader变量调用实例方法之前至少检查.