我无法弄清楚为什么我的代码会出现上述错误。每次调用该方法时,我都会创建一个FileWriter和BufferedWriter的新实例,但显然该流已经关闭。
public static void addSpawn(Location spawn)
{
File spawns = new File("spawns.dat");
FileWriter write = null;
BufferedWriter out = null;
try
{
write = new FileWriter(spawns, true);
out = new BufferedWriter(write);
out.write(locToStr(spawn));
out.newLine();
}
catch(Exception e)
{
System.out.println("Error writing spawn file: " + e.getMessage());
}
finally
{
if(write != null)
{
try
{
write.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(out != null)
{
try
{
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
非常感谢任何帮助。
答案 0 :(得分:2)
BufferedWriter
包裹目标Writer
。当您close()
时,它会在关闭之前尝试flush
基础目标Writer
。
在您的代码中,您在close()
上调用FileWriter
之前,在目标close
上调用BufferedWriter
。当BufferedWriter#close()
尝试在flush
上调用FileWriter
时,FileWriter
已经关闭,从而引发异常。
您希望先关闭BufferedWriter
。更好的是,使用try-with-resources
try (FileWriter write = new FileWriter(spawns, true); BufferedWriter out = new BufferedWriter(write);) {