Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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();
}

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 ---");
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top