1

I have spent countless hours on this one part of my code which is giving me a Null Pointer Exception. I do not understand why it is happening or how to stop it. I have tried every method previously posted on stackoverflow. Here is the function that reads a data file and puts each line in a hashmap.

public ArrayList<HashMap<String, String>> readDataFromFile(){
    this.openFileForReading();
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
    try{
        String line;

        while ((line = this.reader.readLine()) != null){ 

            while (!(line.equals(""))){

                if (line.equals("[type = book]")){
                    HashMap<String, String> data= new HashMap<>();
                    line = this.reader.readLine();

                    while (!(line.equals(""))){<----this is where the null exception error is

                        String tokens[] = line.split("=");
                        data.put(tokens[0], tokens[1]);
                        System.out.println(tokens[0] + " " + tokens[1]);
                        line = this.reader.readLine();

                    }
                   list.add(data);
                }
                else{
                    break;
                }
            }

        }
    }
    catch (IOException exception) {
        list = null;
        System.err.println("(FileIO): " + exception);            
    }
    // Close the file when we have finished reading or if an error occurs
    finally {
        try {
            this.reader.close();                
        } catch (IOException exception) {
            System.err.println("(FileIO): " + exception);
        }
    }

    return list;
}

I then run it in main with this:

public static void main (String args[]) {                                
    FileIO fileIO = new FileIO(DATA_FILE_PATH);
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
    list = fileIO.readDataFromFile();

}
run:

callnumber �QA76.73.J38S265� authors �Walter Savitch, Kenrich Mock� title �Absolute Java� publisher �Addison-Wesley� year �2009� callnumber �P98.C6116� title �Computational Linguistics� Exception in thread "main" java.lang.NullPointerException organization �Association for Computational Linguistics� at librarysearch.FileIO.readDataFromFile(FileIO.java:160) year �2008� at librarysearch.FileIO.main(FileIO.java:405) Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)

I wrote in the code where the error occurs. Why is this happening? I don't understand, if anyone saavy could please help that would be greatly appreciated.

11
  • Post the entire exception with stack trace. Commented Nov 13, 2013 at 21:59
  • Post the full exception tree Commented Nov 13, 2013 at 21:59
  • First thing to do: read the exception stack trace (or post it if you can't understand it). Error messages are intended to be read. They tell you what and where the problem is. By not reading them, you're shooting yourself in the foot, and what could be solved in 10 seconds taks days to be solved. Commented Nov 13, 2013 at 21:59
  • nvm i will edit my main post Commented Nov 13, 2013 at 22:01
  • 2
    Try this while (!("".equals(line))) to avoid NPE. Commented Nov 13, 2013 at 22:06

4 Answers 4

3

You're consuming a new line without checking for null:

 HashMap<String, String> data= new HashMap<>();
 line = this.reader.readLine(); <--- i mean this, and line can be null

 while (!(line.equals(""))){<----this is where the null exception error is

I give you a general advise:

Never compare a String variable against a String literal in this way:

if (myStringWhichCanBeNull.equals("my literal which is never null")) // ...

but always like this:

if ("my literal which is never null".equals(myStringWhichCanBeNull)) // ...

In many cases you will avoid NPE and have more robust code!

(I don't say that in this case this had saved your live...)

Sign up to request clarification or add additional context in comments.

1 Comment

This worked! sort of. I added a while (line != null) before line.equals(") and it now doesnt give an error but stops at the first blank line
1
line = this.reader.readLine();

while (!(line.equals(""))) {

You're reading a line, and then don't check if it's null before calling equals() on it. It will be null if there is nothing to read anymore in the file, as documented in the javadoc of the readLine() method.

Comments

0
 line = this.reader.readLine();

probably returns null on line 13 (unlucky for some)

then you call .equals on it

So maybe add some more error checking

Comments

0

You need to check the result of BufferedReader.readLine() for null everywhere you call the method. As the Java API documentation states, BufferedReader.readLine() 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

Your outer loop checks for null, but you have additional nested loops which perform additional reads but don't check for null. Consider restructuring your code and modifying your logic so you're only using one loop instead of nesting several loops to perform the readLine() operations. Otherwise, you will need to add more null checks and either add break statements or modify your loop conditions, which may make the code more difficult to read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.