Search code examples
javainputstreamfileinputstreamzipinputstream

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?


Solution

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