javainputstreamautocloseable

Closing resource coming as return from method


I have a helper class with a static method that returns a stream:

public static InputStream getDocument(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    return zipFile.getInputStream(zipFile.getEntry("entry"));
}

Another class accesses that method and uses that returned stream:

InputStream is = MyClass.getDocument(new File(str));

My code works.


However, according to the Java Documentation, I should close my resource:

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.

But, when I implement try-with-resources:

public static InputStream getDocument(File file) throws IOException {
    try (ZipFile zipFile = new ZipFile(file);) {
        return zipFile.getInputStream(zipFile.getEntry("entry"));
    }
}

or try-finally:

public static InputStream getDocument(File file) throws IOException {
    InputStream is = null;
    try {
        ZipFile zipFile = new ZipFile(docx);
        is = zipFile.getInputStream(zipFile.getEntry("entry"));
        return is;
    } finally {
        is.close();
    }
}

I get an exception:

java.io.IOException: Stream closed

How to make sure, that resource will be closed, after its use?


Solution

  • Usually the caller is responsible to close/release the resources.
    You can use the try-with-resource or the try-finally construct outside the method as follows:

    try (InputStream is = getDocument(aFile) {
        //… do your stuff
    }
    

    If I can give you an advice, write it in the method documentation:

    /**
      * The caller is required to close the returned {@link InputStream}
      */
    public static InputStream getDocument(File file) throws IOException