我正在使用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();
}
最佳答案
这条线给你扔了NPE
writeHigh.write("0000");
并且只有在捕获到FileNotFoundException的情况下,您才能到达此行。这意味着该行抛出该异常
writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
如果它引发了异常,则表示它执行失败,则尚未实例化writeHigh。因此writeHigh为null。因此
writeHigh.write("0000");
抛出一个NPE。我想你想做
highFile.write("0000");