Closing Streams
suggest changeMost streams must be closed when you are done with them, otherwise you could introduce a memory leak or leave a file open. It is important that streams are closed even if an exception is thrown.
try(FileWriter fw = new FileWriter("outfilename"); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println("the text"); //more code out.println("more text"); //more code } catch (IOException e) { //handle this however you }
Remember: try-with-resources guarantees, that the resources have been closed when the block is exited, whether that happens with the usual control flow or because of an exception.
Sometimes, try-with-resources is not an option, or maybe you’re supporting older version of Java 6 or earlier. In this case, proper handling is to use a finally
block:
FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter("myfile.txt"); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println("the text"); out.close(); } catch (IOException e) { //handle this however you want } finally { try { if(out != null) out.close(); } catch (IOException e) { //typically not much you can do here... } }
Note that closing a wrapper stream will also close its underlying stream. This means you cannot wrap a stream, close the wrapper and then continue using the original stream.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents