java - 关闭 Java 输入/输出流

标签 java file input stream output

这是我的代码:

FileOutputStream fos = null;
DataOutputStream dos = null;
try {
    fos = new FileOutputStream(file);
    dos = new DataOutputStream(fos);

    .... writing to file ....

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (dos != null) {
        try {
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我读到您只需要关闭DataOutpustStream,它将关闭所有其他流,这是正确的吗?如果我无论如何关闭 FileOutputStream 会有什么危害吗?关闭流的最佳方法是什么?

最佳答案

不,它不会造成任何伤害

您需要按照打开它们的顺序关闭它们 - 将它们视为彼此的包装器。如果您创建一个 FileOutputStream,然后将其包装在 DataOutputStream 中,则应首先关闭 DataOutputStream

但是你应该使用try-with-resources:

try (
        final FileOutputStream fos = new FileOutputStream(file);
        final DataOutputStream dos = new DataOutputStream(fos);
) {
    ....writing to file....

} catch (IOException e) {
    e.printStackTrace();
}

如果您以相同的方式处理这两个异常,则只能捕获更通用的 IOException

关于java - 关闭 Java 输入/输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29599593/

相关文章:

c - 从scanf读取不同的输入——C语言

java - 接收 JSON 响应 (android)

java - Lombok - 在实现 equals 和 hashcode 时使用 @Data 发出警告

java - eclipse 动态 web 项目 - 默认起始页

C++ 不能使用另一个文件中的类

c++ - 找到执行文件的目录?

javascript - 根据下拉菜单填充输入表

java - JIMAGE 文件的 JAR 文件 META-INF/MANIFEST.MF 的等价物是什么?

c - C中的读/写函数

html - Fieldset 中的 DIV 层在后台打开而不是前景