-2

I have looked at this question Here and followed the answers. Yet the compiler is still complaining about a Null Pointer Exception. Here is my code blocks as to where the compiler is complaining:

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();
    }
}

The compiler is specifically complaining about this line:

while ((str = reader.readLine()) != null) {

And here is my Main class:

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();
    }
}

I have made the necessary fixes described in the link to the previous questions, yet my compiler is still complaining about it:

ERROR: FILE NOT FOUND!

Exception in thread "main" java.lang.NullPointerException
    at readLogger.readFile(readLogger.java:25)
    at Main.main(Main.java:13)

Nevermind the ERROR as I have exported this to a JAR file and put it in Linux and yet it still throws a NullPointer in Linux. Does anyone have any ideas as to how to fix the NullPointer exception?

Community
  • 1
  • 1
ryekayo
  • 2,341
  • 3
  • 23
  • 51

1 Answers1

5

Your reader variable is null by the time you invoke readLine in statement: while ((str = reader.readLine()) != null) {, since the file is not found (see your own print statement).

Hence you throw a NullPointerException by invoking readLine on a null BufferedReader reference.

The best practice here would be to stop the execution of your readFile method if the file is not found.

As an alternative you might want to at least check for null before invoking instance methods on your reader variable.

Mena
  • 47,782
  • 11
  • 87
  • 106