【问题标题】:DataInputStream who close stream if IOException如果 IOException 关闭流的 DataInputStream
【发布时间】:2013-01-16 20:10:01
【问题描述】:

在所有示例中,每个人都可以找到这样的代码:

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()。当输入数据异常抛出时,此操作会自动执行吗?因为如果程序输入有问题,这意味着流已经打开。

【问题讨论】:

    标签: java datainputstream


    【解决方案1】:

    不,关闭操作不会自动调用。为此,请使用 Java 7 中引入的 try-with-resources:

    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 时会自动调用隐藏 finally 块中的 inputStream 的 close() 方法。

    【讨论】:

    • Java7 中引入的“try-catch-with-resources”是什么意思?在您的代码部分中,我没有看到 inputStream.close() 运算符。你的意思是让 Java 关闭?
    • @LesyaMakhova 我建议您在此处阅读有关此构造的信息:docs.oracle.com/javase/tutorial/essential/exceptions/…
    【解决方案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();
    }
    

    【讨论】:

      【解决方案3】:

      即使出现未找到文件异常,steam 已打开,您也只需再次将其关闭即可。

      您应该始终在 try catch 中添加 finally 块并关闭流。如果有异常,finally 会一直执行

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多