Code Explainers

Code explainers tagged #try-with-resources

java
public List<Path> expandGlob(Path baseDir, String glob) throws IOException {
    FileSystem fs = baseDir.getFileSystem();
    PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
    boolean recursive = glob.contains("**");

Expanding glob patterns with NIO

glob-matching nio streams
Intermediate 5 steps
java
public class AccountRepository {
 
    private final DataSource dataSource;
 

Optimistic locking with a version column in JDBC

optimistic-locking jdbc concurrency
Intermediate 8 steps
java
public final class LogRedactor {
 
    private static final Pattern SECRET = Pattern.compile(
        "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");

Streaming log redaction in Java

regex streaming-io try-with-resources
Intermediate 9 steps
java
public class DuplicateFinder {
 
    public Map<String, List<Path>> findDuplicates(Path root) throws IOException {
        Map<String, List<Path>> byHash = new HashMap<>();

Finding duplicate files by content hash

hashing file-io streams
Intermediate 8 steps
java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

Compressing byte arrays with GZIP in Java

compression streams try-with-resources
Intermediate 6 steps
java
package com.example.inventory;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;

Reading and writing CSV with Commons CSV

csv-parsing file-io try-with-resources
Intermediate 7 steps
java
public List<Employee> parseEmployees(Path csvPath) throws IOException {
    List<Employee> employees = new ArrayList<>();
 
    try (BufferedReader reader = Files.newBufferedReader(csvPath, StandardCharsets.UTF_8)) {

Parsing a CSV into typed objects in Java

csv-parsing file-io try-with-resources
Intermediate 7 steps
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 

Java try-with-resources and AutoCloseable

try-with-resources autocloseable resource-management
Intermediate 6 steps