FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
gis.close();
fis.close();
Is fis.close() necessary? Though I'm running this code and don't seem to get any errors.
The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.
You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.
Yes, they all need to be closed. You could use Java's try-with-resources (docs.oracle.com/javase/tutorial/essential/exceptions/…) to not have to manually close your inputstreams.
You don't have to close ByteArrayInputStream , the moment it is not referenced by any variable, garbage collector will release the stream and somebytes (of course assuming they aren't referenced somewhere else).
You should see the implementation of GZIPInputStream.close()
.
/**
* Closes this input stream and releases any system resources associated
* with the stream.
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (!closed) {
super.close();
eos = true;
closed = true;
}
}
If you take a look at the constructor for GZIPInputStream
, it looks like this:
/**
* Creates a new input stream with the specified buffer size.
* @param in the input stream
* @param size the input buffer size
* @exception IOException if an I/O error has occurred
* @exception IllegalArgumentException if size is <= 0
*/
public GZIPInputStream(InputStream in, int size) throws IOException {
super(in, new Inflater(true), size);
usesDefaultInflater = true;
readHeader(in);
}
Watch the variable in
. Notice how it is being passed to the super class which is InflaterInputStream
in this case.
Now, if we have a look at the implementation of InflaterInputStream.close()
method, we will find this:
/**
* Closes this input stream and releases any system resources associated
* with the stream.
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (!closed) {
if (usesDefaultInflater)
inf.end();
in.close();
closed = true;
}
}
Clearly, in.close()
is being called. So the wrapped (decorated) FileInputStream
is also closed on the call to GZIPInputStream.close()
. Thich makes calling fis.close()
redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With