Java Reference ยท I/O and Files
Closing resources
Patterns for closing files, streams, sockets and connections in Java: try-with-resources, suppressed exceptions, wrapper streams, close order and common leaks.
Files, sockets, database connections and many streams hold something the operating system counts: a file handle, a port, a buffer that still needs flushing. Garbage collection does not close them in time, so you must close them yourself, and close them even when an exception is thrown. The tool for that is try-with-resources, and anything that implements AutoCloseable (or its I/O sibling Closeable) can be used in it.
This page collects the patterns that come up in I/O code. The language rule itself is described on the try-with-resources keyword page and in the AutoCloseable reference.
try (BufferedReader in = Files.newBufferedReader(path); BufferedWriter out = Files.newBufferedWriter(copy)) { in.transferTo(out); } // out is closed first, then in
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Patterns
Declare every resource in the header. Several resources separated by ; close in reverse order of declaration, even if a later constructor throws.
Do not chain constructors inside one declaration unless you also keep the inner object. In new BufferedReader(new FileReader(f)) the FileReader leaks if the BufferedReader constructor throws, which is rare but possible. Put both in the header as separate resources if that matters.
Reuse a variable (Java 9+). try (existingResource) works for a final or effectively final local variable or field.
Return, don't close, when you hand over ownership. If a method creates a stream and returns it, the caller must close it. If you build it and then fail, close it yourself in a catch before rethrowing.
Streams that need closing. Files.lines(), Files.walk(), Files.list() and Files.newDirectoryStream() keep a directory or file open until closed. Wrap them in try-with-resources.
Flush versus close. close() flushes buffered writers first. If close() itself fails, you may have lost data; for important output, call flush() inside the block, or let the exception from close() surface instead of swallowing it.
Executors and clients. ExecutorService has been AutoCloseable since Java 19 (close waits for tasks), HttpClient since 21. Older versions need shutdown() in a finally block.
Usage notes
- The body's exception wins. An exception thrown by
close()while another is in flight is added to the first one as a suppressed exception (getSuppressed()); it is not lost. Closeable.close()is idempotent. Closing a stream twice does nothing.AutoCloseable.close()is not required to be idempotent, and the documentation recommends making it so.- Resources are
finalin the block. You cannot reassign the variable declared in the header. - Null resources are skipped.
try (InputStream in = maybeNull)is fine; nothing is closed if it isnull. - Catch after, not inside. A
catchorfinallyattached to the sametryruns after the resources are closed. If you need to log something while the resource is still open, nest atry. - Do not close
System.in,System.outorSystem.errcasually; later code in the program cannot use them again. - Leaks are silent. Leaked file handles show up much later as "Too many open files". Tools such as static analysis in your IDE flag unclosed resources.
- Virtual threads and blocking I/O do not change anything: you close resources the same way.
finallyis still valid for non-AutoCloseableclean-up such as unlocking aLock.