检查FileInputStream是否已关闭的最佳方法是什么?

时间:2017-04-19 09:00:51

标签: java inputstream fileinputstream zipinputstream

所以我创建 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对象会发生什么?有没有办法测试这个?

2 个答案:

答案 0 :(得分:3)

如果你正在使用java 7,最佳做法是使用'尝试使用资源'块。 所以资源将自动关闭。

考虑下面的例子:

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

答案 1 :(得分:0)

这应该是使用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语句   确保在语句结束时关闭每个资源。

相关问题