写文件:IOException:Stream关闭

时间:2014-08-30 20:07:22

标签: java ioexception filewriter

我无法弄清楚为什么我的代码会出现上述错误。每次调用该方法时,我都会创建一个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();
            }
        }
    }
}

非常感谢任何帮助。

1 个答案:

答案 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);) {