Java
try-with-resources
Learn automatic close with try-with-resources.
try-with-resources
Introduced in Java 7, try-with-resources automatically closes resources like files. The resource is declared at the start of the try block; when the block ends, Java calls close() automatically. The BufferedReader r = new BufferedReader(...) resource goes inside the try parentheses.
This structure removes the risk of forgetting close(). The resource must implement AutoCloseable; most Java I/O classes do. Multiple resources are separated by semicolons.
The AutoCloseable interface
For a class to be used in try-with-resources, it must implement AutoCloseable. This interface has one method: void close() throws Exception. When you write your own resource classes, you implement this interface and override close.
If the try block throws and close also throws, the close exception is added as suppressed to the main exception; it is not lost. Access it with Throwable.getSuppressed().
Exercise Read a file with try-with-resources
Import java.io.BufferedReader, java.io.FileReader, java.io.FileWriter and java.io.IOException. Add throws IOException to main. First write a file: FileWriter fw = new FileWriter("k.txt"); fw.write("Line"); fw.close();. The main task: in a try (BufferedReader r = new BufferedReader(new FileReader("k.txt"))) block, print System.out.println(r.readLine());. Do not call close; try-with-resources handles it.
Show example solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("k.txt");
fw.write("Line");
fw.close();
try (BufferedReader r = new BufferedReader(new FileReader("k.txt"))) {
System.out.println(r.readLine());
}
}
}
Test yourself
-
Complete the try-with-resources header
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"____)) {
System.out.println(r.readLine());
}
Show answer
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(r.readLine());
}
-
What does try-with-resources guarantee?
- The resource is never opened
- Exceptions are never thrown
- The file is deleted automatically
- The resource is closed automatically
Show answer
The resource is closed automatically — try-with-resources calls close automatically at the end of the block.
-
Match the try-with-resources concepts
- AutoCloseable
- Interface required for resources
- close()
- Method called automatically
- suppressed
- Exception from close, attached
- try (...)
- Resource declaration
Next lesson: Summary - File I/O