乍一看,这代码似乎完全OK是否可以安全使用java.io.BufferedOutputStream?
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("1.txt"));
byte[] bytes = new byte[4096];
bout.write(bytes);
bout.close();
但如果我们仔细看,我们会看到如下
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
有没有可能是由于flush()
错误被忽略的close()
实现数据可能会丢失,程序不会注意到它? FilterOutputStream.close
(其中BufferedOutputStream
继承自close()
)没有提及任何危险。
UPDATE:为了在靠近模拟IO误差(),我改变了测试写入到闪存,加入bout.close之前5秒睡眠()和在测试正在睡觉我从USB移除闪存。测试没有例外,但是当我插入Flash并检查它时 - 1.txt不存在。
然后我推翻的close()
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("g:/1.txt")) {
@Override
public void close() throws IOException {
flush();
super.close();
}
};
并再次运行测试,并得到
Exception in thread "main" java.io.FileNotFoundException: g:\1.txt (The system cannot the specified path)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at test.Test1.main(Test1.java:10)
'FilterOutputStream' typo? –
它显示为openjdk'close()'方法中的一个错误。 - 死商店忽略... –
@Nikolay没有它没有。 BufferedOuptutStream从那里继承,忘记提及 –