A subclass of Writer or OutputStream that is opened for writing but not properly closed later may cause a resource leak.

Ensure that the resource is always closed to avoid a resource leak. Note that, because of exceptions, it is safest to close a resource properly in a finally block. (However, this is unnecessary for subclasses of CharArrayWriter, StringWriter and ByteArrayOutputStream.)

For Java 7 or later, the recommended way to close resources that implement java.lang.AutoCloseable is to declare them within a try-with-resources statement, so that they are closed implicitly.

In the following example, the resource bw is opened but not closed.

In the following example, the resource bw is opened in a try block and later closed in a finally block.

Note that nested class instance creation expressions of Writers or OutputStreams are not safe to use if the constructor of the outer expression may throw an exception. In the following example, the OutputStreamWriter may throw an exception, in which case the inner FileOutputStream is not closed.

In this case, the inner expression needs to be assigned to a local variable and closed separately, as shown below.

  • IBM developerWorks: Java theory and practice: Good housekeeping practices.
  • The Java Tutorials: The try-with-resources Statement.