1

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.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Lesya Makhova
  • 1,340
  • 3
  • 14
  • 28

3 Answers3

2
DataInputStream inputStream = null;
try {
    inputStream = new DataInputStream( new FileInputStream("file.data"));
    int i = inputStream.readInt();
} catch (FileNotFoundException e) { 
  //print message File not found
} catch (IOException e) { 
  e.printStackTrace();
} finally{
  if(null!=inputStream)
    inputStream.close();
}
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
2

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.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • what do you mean "try-catch-with-resources" introduced in Java7? in your code part I don't see inputStream.close() operator. you mean to let closing for Java? – Lesya Makhova Jan 16 '13 at 20:17
  • 2
    @LesyaMakhova I suggest you to read about this construction here: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Andremoniy Jan 16 '13 at 20:18
2

Even if the file not found exception occurs the steam is open, you would simply need to close it again as well.

You should always add a finally block in your try catch and close the stream. Finally will always execute if there is an exception

 finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    //do something clever with the exception
                }
            }
            System.out.println("--- File End ---");
        }
tam tam
  • 1,870
  • 2
  • 21
  • 46