这是我的代码:
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/