In all examples everybody can find code like this:
DataInputStream inputStream = null;
try {
inputStream = new DataInputStream( new FileInputStream("file.data"));
int i = inputStream.readInt();
inputStream.close();
} catch (FileNotFoundException e) {
//print message File not found
} catch (IOException e) { e.printStackTrace() }
When this code met FileNotFound exception, inputStream was not open, so it doesn’t need to be closed.
But why when IOException mets in that catch block I don’t see inputStream.close(). This operation did’s automatically when input data exception throws? Because if programm has problem with input this means that stream already open.
No, close operation doesn’t invoke automatically. For this purposes use
try-with-resourcesintroduced in Java 7:UPD: Explanation:
DataInputStreamimplementsAutoCloseableinterface. That means, that in constructiontry-with-resourcesJava automatically will callclose()method ofinputStreamin hidden finally block.