Part 07 / Topic 5 of 7
try-with-resources for real I/O resources
Part 6 introduced try/catch/finally. try-with-resources is a try that also opens one or more resources — anything implementing AutoCloseable — in parentheses right after try, and guarantees every one of them is closed when the block ends, even if an exception is thrown partway through. BufferedReader and BufferedWriter (and every I/O stream/reader/writer in the JDK) implement AutoCloseable.
Think of borrowing library books: try-with-resources is the automatic return slot — the books go back the moment you're done, whether you finished reading or not.
You can open more than one resource in the same try; they close in reverse order automatically:
try (BufferedReader reader = Files.newBufferedReader(source);
BufferedWriter writer = Files.newBufferedWriter(report)) {
String line;
double total = 0;
int count = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
double amount = Double.parseDouble(parts[1]);
total += amount;
count++;
writer.write(parts[0] + " paid ₹" + amount);
writer.newLine();
}
writer.write("TOTAL for " + count + " orders: ₹" + total);
writer.newLine();
} catch (IOException e) {
System.out.println("I/O problem: " + e.getMessage());
}
With data/orders.txt containing:
Ravi,1200
Asha,3400
Meera,850
Ravi,500
the report written to data/report.txt is:
Ravi paid ₹1200.0
Asha paid ₹3400.0
Meera paid ₹850.0
Ravi paid ₹500.0
TOTAL for 4 orders: ₹5950.0
A missing file is just another IOException
Opening a file that does not exist does not crash the program — it throws a checked exception (specifically NoSuchFileException, a subtype of IOException), which you catch exactly like any other checked exception from Part 6:
Path missing = dataDir.resolve("does-not-exist.txt");
try (BufferedReader missingReader = Files.newBufferedReader(missing)) {
System.out.println(missingReader.readLine());
} catch (IOException e) {
System.out.println("Caught " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output:
Caught NoSuchFileException: data/does-not-exist.txt
| Method | Returns | Good for |
|---|---|---|
Files.newBufferedReader(path) |
BufferedReader |
reading a file line by line, without loading it all into memory first |
Files.newBufferedWriter(path) |
BufferedWriter |
writing a file line by line (write(text) then newLine()) |
Full program: examples/ex03-try-with-resources-io/ResourceDemo.java.
Done here? The practice set for Part 7 — including the solutions — is on the part page.