javabeginner
Try-With-Resources and AutoCloseable
Manage resources safely with try-with-resources: files, connections, streams, and custom resources.
javaPress ⌘/Ctrl + Shift + C to copy
import java.io.*;
import java.sql.*;
import java.net.http.*;
import java.net.URI;
public class ResourceManagement {
// 1. File I/O — auto-closed
static void readFile(String path) throws IOException {
try (var reader = new BufferedReader(new FileReader(path))) {
reader.lines().forEach(System.out::println);
} // reader.close() called automatically
}
// 2. Multiple resources
static void copyFile(String src, String dst) throws IOException {
try (
var in = new BufferedInputStream(new FileInputStream(src));
var out = new BufferedOutputStream(new FileOutputStream(dst))
) {
in.transferTo(out);
}
}
// 3. JDBC connection
static void queryDb(String url) throws SQLException {
try (
Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE age > ?");
) {
stmt.setInt(1, 18);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}
// 4. Custom AutoCloseable
static class Timer implements AutoCloseable {
private final String label;
private final long start;
Timer(String label) {
this.label = label;
this.start = System.nanoTime();
System.out.println("START: " + label);
}
@Override
public void close() {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("END: %s (%d ms)%n", label, ms);
}
}
public static void main(String[] args) throws Exception {
try (var timer = new Timer("demo")) {
Thread.sleep(100);
} // prints: END: demo (100 ms)
}
}Use Cases
- Safe resource management preventing leaks
- JDBC connection lifecycle management
- Performance timing with custom AutoCloseable
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javabeginner
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
#java#string
javabeginner
Java Optional — Avoid NullPointerException
Use Optional to handle nullable values safely with map, flatMap, orElse, and ifPresent patterns.
Best for: Eliminating NullPointerException in business logic
#java#optional
javabeginner
Java Date/Time API — Modern Operations
Work with LocalDate, LocalDateTime, ZonedDateTime, Duration, Period, and date formatting.
Best for: Date arithmetic and business day calculations
#java#date-time
javaintermediate
Java Enums — Methods, Fields, and Interfaces
Advanced enum patterns: enums with fields, abstract methods, implementing interfaces, and enum maps.
Best for: Type-safe constants with behavior
#java#enums