在finally块中用java关闭文件的最好、最干净的方法是什么

piok6c0g  于 2021-06-26  发布在  Java
关注(0)|答案(2)|浏览(265)

我编写了一个方法来关闭对文件的写入。但是,一位高级开发人员建议我关闭finally块中的文件。
这是我的方法:

private static void writetoFiles(String error) {
    try {
        File file = new File("errorcode.txt");
        if (!file.exists()) {
            file.createNewFile();
    } else {
            FileWriter updateerrorcode = new FileWriter("errorcode.txt");
            updateerrorcode.write(error);
            updateerrorcode.close();
     }
    } catch (IOException e) {
    }
}

我在stackoverflow中读到了很多答案,但对于我这样一个简单的案例来说,所有的答案似乎都有点太复杂了。有什么建议我该怎么做?

uqxowvwt

uqxowvwt1#

使用try with resource语句:

private static void writetoFiles(String error) {
    try {
        File file = new File("errorcode.txt");
        if (!file.exists()) {
            file.createNewFile();
        } else {
            try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
                updateerrorcode.write(error);
            }
        }
    } catch (IOException e) {
        // TODO: Handle error condition
    }
}

要指出一个单独的问题…我认为你的例子中的逻辑是错误的。如果输出文件不存在,那么代码所做的就是创建该文件。只有当文件已经存在时,它才会写入 error 给它发短信。我想无论哪种情况你都想写这篇文章。如果这是真的,你不需要 createNewFile 打电话给我 FileWriter 类将创建该文件(如果该文件尚不存在)。所以我认为你真正想要的是:

private static void writetoFiles(String error) {
    try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
        updateerrorcode.write(error);
    } catch (IOException e) {
        // TODO: Handle error condition
    }
}

这将导致写入程序在正常执行情况和错误抛出情况下都正确关闭。我假设在你的实际代码中,你会做一些事情 IOException 当它被抓住的时候。我不知道你想在那里干什么,所以我什么也不提。
如果你想严格使用 finally 块,您可以这样做:

FileWriter updateerrorcode = new FileWriter("errorcode.txt");
try {
    updateerrorcode.write(error);
}
catch (IOException e) {
    // TODO: Handle error condition
}
finally {
    updateerrorcode.close();
}

在添加try-with-resource构造之前,这是java早期版本中唯一的选项。在第二种方法中,您可能希望从 close() ,但在我25多年的java经验中,我不记得 close() 调用文件失败。我想如果目标卷上的磁盘空间不足,你会得到这样的结果 close() 无法刷新流的写入缓冲区。这个问题是新方法的一个明显优点…关闭文件失败不会影响 write() 打电话。

lvjbypge

lvjbypge2#

最干净的方法是使用try with resources语句,如下所示:

private static void writetoFiles(String error) throws IOException {
    //...

    try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
        updateerrorcode.write(error);
    }

    //...
}

如果方法无法处理异常,请不要捕获该异常:
如果这个方法, writetoFiles 无法处理异常,它应该抛出相同的异常,以便调用方法可以适当地处理它。

相关问题