java.lang.NullPointException 使用 FileWriter
java.lang.NullPointException using FileWriter
我正在使用 BufferedWriter
在 class 的构造函数中写入新创建的文本文件。 class 创建文本文件,然后向其中添加初步文本,这样读取操作就不会 return 出错。但是,当我尝试添加此初步文本时,特别是在下面的方法中使用 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();
}
如果失败
writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
writeHigh 后来为空
您似乎在第一个尝试小组中有一个 "FileNotFoundException"。此点 "writeHigh " 为空,并且您在 "writeHigh.write" 调用
之前未设置其他值
这条线给你一个 NPE
writeHigh.write("0000");
并且只有在捕获到 FileNotFoundException 时才会到达此行。这意味着这一行抛出了那个异常
writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
如果抛出异常,说明执行失败,说明writeHigh还没有实例化。所以 writeHigh 为空。所以 writeHigh.write("0000");
抛出一个 NPE。
我想你想做的事
highFile.write("0000");
我正在使用 BufferedWriter
在 class 的构造函数中写入新创建的文本文件。 class 创建文本文件,然后向其中添加初步文本,这样读取操作就不会 return 出错。但是,当我尝试添加此初步文本时,特别是在下面的方法中使用 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();
}
如果失败
writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
writeHigh 后来为空
您似乎在第一个尝试小组中有一个 "FileNotFoundException"。此点 "writeHigh " 为空,并且您在 "writeHigh.write" 调用
之前未设置其他值这条线给你一个 NPE
writeHigh.write("0000");
并且只有在捕获到 FileNotFoundException 时才会到达此行。这意味着这一行抛出了那个异常
writeHigh = new BufferedWriter(new FileWriter(HIGH_SCORE_PATH, false));
如果抛出异常,说明执行失败,说明writeHigh还没有实例化。所以 writeHigh 为空。所以 writeHigh.write("0000");
抛出一个 NPE。
我想你想做的事
highFile.write("0000");