Resource cleanup
What you will learn
A file handle, directory stream or channel must be released even when processing fails. Use try-with-resources for handles and a separate finally for deleting files owned by your program. Closing a stream is not the same operation as deleting its file.
- Use try-with-resources for file and directory handles.
- Distinguish closing, flushing and deleting.
- Verify cleanup after successful and failed operations.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Run in a fresh lab-owned working directory. Examples create a unique child directory and delete fixed fixture names in finally. Symlink and atomic-move examples require corresponding filesystem support. The item helper validates leaf names; bounded reads at most max plus one byte.
Close a writer before reading
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"a.txt"); try (BufferedWriter writer = Files.newBufferedWriter(file,StandardCharsets.UTF_8)) { writer.write("ready"); } System.out.println(Files.readString(file)); System.out.println(Files.deleteIfExists(file)); System.out.println(Files.deleteIfExists(file)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
readytruefalseThe closed writer leaves the file present. deleteIfExists tells whether an entry was deleted.
Ownership and close order
The code that opens a handle normally owns closing it, unless its contract transfers ownership. Try-with-resources closes successfully initialized resources in reverse order. A wrapper often closes its underlying stream; avoid using that underlying stream afterward. An exception while closing is suppressed when the body has already thrown. Do not ignore close errors, especially for writers where buffered output may fail late.
Separate resource lifetime from file lifetime
After closing a writer, reading its file sees the written data under the ordinary local fixture conditions. Closing does not remove a file. Use finally to delete precisely the entries you created, then the empty directory. Do not recursively delete user-supplied paths. If cleanup itself can fail, preserve and report the primary exception and cleanup failures; a plain finally can mask a primary failure. The simple fixture cleanup here assumes a private directory and no concurrent writers.
Streams and watchers
Files.lines, Files.list and DirectoryStream all require closing. Do not return a lazy stream backed by a handle already closed by its creator. A WatchService registers directories and yields keys containing events; reset a processed key and close the service. Events can be coalesced, lost (OVERFLOW), or delayed, so rescan on uncertainty. Do not infer exact event counts or use a watcher as a security audit. Watching is described only; asynchronous behavior is not executed here.
Close a lazy file stream
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"a.txt"); Files.writeString(file,"book\npen\nbook\n"); try (var lines = Files.lines(file,StandardCharsets.UTF_8)) { System.out.println(lines.filter("book"::equals).count()); } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
2The terminal operation does not replace closing the stream; the try owns it.
Release after a processing failure
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"a.txt"); Files.writeString(file,"not-a-number"); try (BufferedReader reader = Files.newBufferedReader(file)) { Integer.parseInt(reader.readLine()); } catch (NumberFormatException e) { System.out.println("invalid quantity"); } finally { Files.deleteIfExists(file); } System.out.println(Files.notExists(file,LinkOption.NOFOLLOW_LINKS)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
invalid quantitytrueThe reader is closed before the catch and finally; deletion occurs even after parsing fails.
Preserve the original exception
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; } static final class FailingResource implements AutoCloseable { void process() throws IOException { throw new IOException("processing failed"); } @Override public void close() throws IOException { throw new IOException("close failed"); } } public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { try (var resource = new FailingResource()) { resource.process(); } catch (IOException e) { System.out.println(e.getMessage()); System.out.println(e.getSuppressed()[0].getMessage()); } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
processing failedclose failedThe deliberately simulated close failure is preserved as a suppressed exception.
Common mistakes
Do not rely on garbage collection to close files. Do not swallow IOException or assume flushing guarantees power-loss durability. Avoid opening a directory stream without a try-with-resources scope.
Practice
Write two lines to a.txt, count the lines in a try-with-resources Files.lines stream, delete a.txt, and print the count and whether deletion succeeded.
Expected output:
2trueCompare your answer with the manual practice criteria.
Official reading: Files · BufferedWriter · WatchService. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Resource cleanup — knowledge check
Original filesystem and I/O questions. Java 21-compatible scope.
When does try-with-resources close the reader?
What does close do to a regular file opened for writing?
Which lazy stream must be closed?
What happens to a close failure when the body already threw?
How should a watch overflow be handled?