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

What is the best way to check if a FileInputStream is closed?

所以我有创建 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 对象发生了什么?有什么方法可以测试吗?

这应该是使用 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

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

如果您使用 java 7,最佳做法是使用 'try with resources' 块。 所以资源将被自动关闭。

考虑以下示例:

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