【问题标题】:What is the best way to check if a FileInputStream is closed?检查 FileInputStream 是否关闭的最佳方法是什么?
【发布时间】:2017-04-19 09:00:51
【问题描述】:

所以我有创建 ZipInputStream 所需的 FileInputStream,我想知道如果 ZipInputStream 会发生什么>FileInputStream 已关闭。考虑以下代码:

public void Foo(File zip) throws ZipException{
     ZipInputStream zis;
     FileInputStream fis = new FileInputStream(zip);

     try{
         zis = new ZipInputStream(fis);
     } catch (FileNotFoundException ex) {
         throw new ZipException("Error opening ZIP file for reading", ex);
     } finally {
         if(fis != null){ fis.close(); 
     }
}

zis 是否仍然打开? ZipInputStream 对象会发生什么?有什么方法可以测试吗?

【问题讨论】:

  • zis 保持打开状态.. 你必须明确关闭它
  • 有办法测试吗?

标签: java inputstream fileinputstream zipinputstream


【解决方案1】:

如果您使用的是 java 7,最佳做法是使用“try with resources”块。 所以资源会自动关闭。

考虑以下示例:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
               new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

【讨论】:

    【解决方案2】:

    这应该是使用 java 7 中可用的 try with resource 块的正确方法。

    这样资源(fis和zis)会在try块结束时自动关闭。

    try (FileInputStream fis = new FileInputStream(zip);  
         ZipInputStream zis = new ZipInputStream(fis)) 
    {
       // Do your job here ...
    } catch (FileNotFoundException ex) {
       throw new ZipException("Error opening ZIP file for reading", ex);
    } 
    

    The try-with-resources Statement

    try-with-resources 语句是一个 try 语句,它声明一个 或更多资源。资源是必须在之后关闭的对象 该程序已完成。 try-with-resources 语句 确保每个资源在语句结束时关闭。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 2011-05-25
      • 2012-08-29
      • 2011-03-20
      • 2011-12-25
      相关资源
      最近更新 更多