Closing Streams

suggest change

Most 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 want
}

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 Java 6 or earlier. In this case, proper handling is to use a finally block. Close the outermost stream that was actually created: if constructing PrintWriter fails, out is still null and the earlier writers would leak.

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");
} catch (IOException e) {
    //handle this however you want
}
finally {
    if (out != null) {
        out.close(); // PrintWriter.close() does not throw IOException
    } else if (bw != null) {
        try {
            bw.close();
        } catch (IOException e) {
            //typically not much you can do here...
        }
    } else if (fw != null) {
        try {
            fw.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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents