Robert Ivan
Robert Ivan

Reputation: 19

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

So I have this FileInputStream that is required to create a ZipInputStream and I want to know what happens to the ZipInputStream if the FileInputStream is closed. Consider the following code:

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(); 
     }
}

Does zis remais open? What happens to the ZipInputStream object? Is there a way I can test this?

Upvotes: 0

Views: 2243

Answers (2)

freedev
freedev

Reputation: 30057

This should be the right way using try with resource block available from java 7.

In this way the resources (fis and zis) will be closed automatically at end of try block.

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.

Upvotes: 1

sovas
sovas

Reputation: 1578

If you're using java 7, the best practice is to use 'try with resources' block. So resource will be auto closed.

Consider the folowing example:

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

Upvotes: 3

Related Questions