I am working with HSSFWorkbook
and I wanted to know where should I close the InputStream
object that I have used while constructing the HSSFWorkbook
object. Does HSSFWorkbook closes the stream in its constructor itself? or do we need to close it manually? And can we close it just after the constructor call? i.e., does HSSFWorkbook
object use the InputStream
object in its constructor only? or can it also use it in future (in this case we cant close it)? thank you.
public HSSFWorkbook loadSheet(File file) throws FileNotFoundException, IOException {
return new HSSFWorkbook(new FileInputStream(file));
}
The constructor of HSSFWorkbook
doesn't state whether the InputStream
will be closed or left open, so at a first glance you shouldn't make assumptions that it's going to be closed. Digging deeper, however, the constructor of a class used within the constructor itself on the other hand does state clearly its behaviour.
At least in Apache POI 4.0.0 the call to new HSSFWorkbook(inputStream)
will result in a call to new POIFSFileSystem(inputStream)
which, in its implementation, does indeed appear to always close the stream and the constructor documentation confirms it.
This would seem to point to the following answers to your questions:
HSSFWorkbook
closes the stream in its constructor itself? Yes, indirectly.POIFSFileSystem
, which seems unlikely.HSSFWorkbook
object use the InputStream
object in its constructor only? Apparently so.