2013-01-23 80 views
20

乍一看,这代码似乎完全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) 
+0

'FilterOutputStream' typo? –

+3

它显示为openjdk'close()'方法中的一个错误。 - 死商店忽略... –

+0

@Nikolay没有它没有。 BufferedOuptutStream从那里继承,忘记提及 –

回答

5

正因为如此,我有理由相信调用close的确可以使你丢失数据,因为这潜在的IOException正在默默无视(谁知道开发人员想要做什么......)。

一个体面的选择,尽管它把精力程序员的身边,是close之前显式调用flush(正确地处理潜在IOException),如由@汤姆的评论中提到,特别是在try/finally块。

在Java7中,由于AutoCloseable对象,此问题可能会进一步加剧,因为您不会明确调用close()方法,并且此类解决方法更容易解决。

+0

,可能是因为它们没有抑制异常,所以他们不知道如何处理来自flush()的异常。 – irreputable

+1

我认为将Exception抛出并让用户明确知道出现问题会更安全。 – pcalcao

相关问题