2017-04-19 180 views
0

所以我有这个的FileInputStream所需创建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 remais打开? ZipInputStream对象会发生什么?有什么方法可以测试这个吗?

+0

'zis'保持打开..你必须关闭它明确 –

+0

有没有办法来测试? –

回答

3

如果您使用的是java 7,最好的做法是使用'try with resources'块。 因此资源将被自动关闭。

考虑如下因素例如:

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

这应该是使用可从Java 7中

这样的资源(FIS和ZIS)将自动在try块的年底前关闭try with resource块的正确途径。

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语句。资源是在程序完成后必须关闭的对象。 try-with-resources语句 可确保在语句结束时关闭每个资源。

相关问题