capypad
0 day streak
java / intermediate
Snippet

Automatic Resource Management

The try-with-resources statement ensures that each resource is closed at the end of the statement, preventing memory leaks and resource exhaustion.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
import java.io.*;
 
public class TryWithResources {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Breakdown
1
try (BufferedReader br = ...)
Declares a resource that implements AutoCloseable to be managed automatically.
2
catch (IOException e)
Handles potential errors during file reading or resource closing.