Search code examples
javadatainputstream

DataInputStream who close stream if IOException


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.


Solution

  • No, close operation doesn't invoke automatically. For this purposes use try-with-resources introduced in Java 7:

    try (DataInputStream inputStream = new DataInputStream( new FileInputStream("file.data"))) {
        int i = inputStream.readInt();
    } catch (Exception e) { e.printStackTrace() }      
    

    UPD: Explanation: DataInputStream implements AutoCloseable interface. That means, that in construction try-with-resources Java automatically will call close() method of inputStream in hidden finally block.