2013-01-16 67 views
1

在所有案例中每个人都可以像这样找代码:DataInputStream类谁关闭流,如果IOException异常

DataInputStream inputStream = null; 
try { 
    inputStream = new DataInputStream(new FileInputStream("file.data")); 
    int i = inputStream.readInt(); 
    inputStream.close(); 
} catch (FileNotFoundException e) { 
    //print message File not found 
} catch (IOException e) { e.printStackTrace() } 

此代码时遇到FileNotFound例外,inputStream没有打开,所以它并不需要关闭。

但是为什么当IOException在那个catch块我看不到inputStream.close()。当输入数据异常抛出时,这个操作会自动执行吗?因为如果程序有输入问题,这意味着流已经打开。

回答

2

不,关闭操作不会自动调用。为了这个目的,使用try-with-resources在Java 7中介绍:

try (DataInputStream inputStream = new DataInputStream(new FileInputStream("file.data"))) { 
    int i = inputStream.readInt(); 
} catch (Exception e) { e.printStackTrace() }  

UPD:说明:DataInputStream实现AutoCloseable接口。也就是说,在构建try-with-resources时Java自动会调用close()的方法inputStream在隐藏finally块。

+0

你是什么意思在Java7中引入“try-catch-with-resources”?在你的代码部分我没有看到inputStream.close()运算符。你的意思是让Java关闭? –

+2

@LesyaMakhova我建议你阅读这里的建设:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Andremoniy

+0

非常感谢。这是最好的解决方案! –

2
DataInputStream inputStream = null; 
try { 
    inputStream = new DataInputStream(new FileInputStream("file.data")); 
    int i = inputStream.readInt(); 
} catch (FileNotFoundException e) { 
    //print message File not found 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally{ 
    if(null!=inputStream) 
    inputStream.close(); 
} 
2

即使文件没有找到异常发生蒸汽打开,你只需要再次关闭它。

您应该总是在try catch中添加一个finally块并关闭流。如果有异常,最后总是会执行

finally { 
      if(reader != null){ 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        //do something clever with the exception 
       } 
      } 
      System.out.println("--- File End ---"); 
     }