Search code examples
javaionullpointerexceptionfile-writing

java.lang.NullPointException using FileWriter


I'm writing to a newly created text file in the constructor of a class using BufferedWriter. The class creates the text file, and then adds preliminary text to it so that read operations don't return an error. When I try to add this preliminary text, however, specifically using writeHigh in the method below, I receive a java.lang.NullPointerException. I don't think this has anything to do with the string I'm passing in, but I've also tried changing my instantiations of writeHigh, which did nothing. I was hoping someone might know what the cause of this error is. The stack trace is not helping.

    try
    {   
        //New buffered writters that can write to the specified files.
        writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));

        //highScore = Integer.parseInt(readScore.readLine());
    }
    catch(FileNotFoundException e) //If reading from these files fails because they don't yet exist...
    {
        File highFile = new File(HIGH_SCORE_PATH); //Create a new high score file, this is the first time the game has been played.

       try
       {
           highFile.createNewFile();
           writeHigh.write("0000"); //This line is throwing the error
       }
       catch(IOException i)
       {
           i.printStackTrace();
       }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

Solution

  • This line is throwing you a NPE

    writeHigh.write("0000");
    

    And you reach this line only if you've catched a FileNotFoundException. Which means that this line as thrown that exception

    writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
    

    If it has thrown an exception, it means it has failed to execute, then writeHigh hasn't been instantiated. So writeHigh is null. And so writeHigh.write("0000"); throw a NPE.


    I think you wanted to do

    highFile.write("0000");