使用FileWriter的java.lang.NullPointException

时间:2018-05-29 14:15:40

标签: java io nullpointerexception file-writing

我使用BufferedWriter在类的构造函数中写入新创建的文本文件。该类创建文本文件,然后向其添加初步文本,以便读取操作不会返回错误。但是,当我尝试添加此初步文本时,特别是在下面的方法中使用writeHigh时,我会收到java.lang.NullPointerException。我不认为这与我传入的字符串有任何关系,但我也尝试更改writeHigh的实例化,它没有做任何事情。我希望有人可能知道这个错误的原因是什么。堆栈跟踪没有帮助。

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

3 个答案:

答案 0 :(得分:1)

这一行给你一个NPE

writeHigh.write("0000");

只有在您捕获到FileNotFoundException时才能到达此行。这意味着这一行抛出异常

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

如果它抛出异常,则表示它无法执行,然后writeHigh尚未实例化。所以writeHigh为null。所以writeHigh.write("0000");抛出一个NPE。

我想你想做

highFile.write("0000");

答案 1 :(得分:0)

如果失败

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

writeHigh后来为空

答案 2 :(得分:0)

似乎你在第一次尝试集团中有一个“FileNotFoundException”。这一点“writeHigh”为空,你不能在“writeHigh.write”调用之前设置另一个值