Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java try finally block to close stream

I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally block in order to close the stream. Is that the right way to do it? It seems a bit clunky.

Here's the code:

 public void read() {     try {         r = new BufferedReader(new InputStreamReader(address.openStream()));         String inLine;         while ((inLine = r.readLine()) != null) {             System.out.println(inLine);         }     } catch (IOException readException) {         readException.printStackTrace();     } finally {         try {             if (r!=null) r.close();         } catch (Exception e){             e.printStackTrace();         }     }   } 
like image 953
jhlu87 Avatar asked Aug 28 '11 23:08

jhlu87


People also ask

Why you need to close the stream in finally block?

This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side.

How do you close streams in Java?

You only need to close streams that use IO resources. From the Stream documentation: Streams have a BaseStream. close() method and implement AutoCloseable , but nearly all stream instances do not actually need to be closed after use.

Which exception is thrown when the stream is closed in finally block?

Don't close in finally block The close method can throw an IOException and FileInputStream / ObjectInputStream can be null. When you use . close in finally , you must check null and try/catch again.

Does finally {} block always run?

A finally block always executes, regardless of whether an exception is thrown.


1 Answers

Also if you're using Java 7, you can use a try-with-resources statement:

try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) {     String inLine;     while ((inLine = r.readLine()) != null) {         System.out.println(inLine);     } } catch(IOException readException) {     readException.printStackTrace(); }            
like image 123
Bugasu Avatar answered Oct 13 '22 14:10

Bugasu