try-with-resources案例

wen java案例 1

本文目录导读:

try-with-resources案例

  1. 基础用法:文件操作
  2. 多资源管理
  3. 自定义资源类
  4. 资源与异常处理
  5. 网络资源管理
  6. 互斥锁资源
  7. 结合Lambda表达式
  8. 数据库连接管理(模拟)
  9. 实际项目中的完整示例
  10. 高级技巧:封装资源管理

我来为你展示Java中try-with-resources的多个实用案例,从基础到高级。

基础用法:文件操作

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BasicExample {
    public static void main(String[] args) {
        // 自动关闭文件资源
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多资源管理

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class MultiResourceExample {
    public static void copyFile(String source, String target) {
        // 同时管理多个资源,按声明顺序逆序关闭
        try (InputStream in = Files.newInputStream(Paths.get(source));
             OutputStream out = Files.newOutputStream(Paths.get(target))) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            System.err.println("复制失败: " + e.getMessage());
        }
    }
}

自定义资源类

public class CustomResourceExample {
    // 自定义资源类,实现 AutoCloseable 接口
    static class DatabaseConnection implements AutoCloseable {
        private String name;
        public DatabaseConnection(String name) {
            this.name = name;
            System.out.println("打开数据库连接: " + name);
        }
        public void query(String sql) {
            System.out.println("执行查询: " + sql);
            if (sql.contains("error")) {
                throw new RuntimeException("查询失败!");
            }
        }
        @Override
        public void close() {
            System.out.println("关闭数据库连接: " + name);
        }
    }
    public static void main(String[] args) {
        // 无论是否发生异常,都会自动关闭资源
        try (DatabaseConnection conn = new DatabaseConnection("Oracle")) {
            conn.query("SELECT * FROM users");
            conn.query("error - 触发异常");
        } catch (RuntimeException e) {
            System.out.println("捕获异常: " + e.getMessage());
        }
    }
}

资源与异常处理

import java.io.*;
public class ExceptionHandlingExample {
    // 演示 suppress exception(被抑制的异常)
    public static void showSuppressedExceptions() {
        try (BufferedReader reader = new BufferedReader(
                new FileReader("nonexistent.txt"))) {
            String line = reader.readLine();
        } catch (IOException e) {
            System.out.println("主异常: " + e.getMessage());
            Throwable[] suppressed = e.getSuppressed();
            if (suppressed.length > 0) {
                System.out.println("被抑制的异常数量: " + suppressed.length);
                for (Throwable t : suppressed) {
                    System.out.println("  抑制异常: " + t.getMessage());
                }
            }
        }
    }
    // 传统方式的对比
    public static void traditionalWay() throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("test.txt"));
            String line = reader.readLine();
        } finally {
            if (reader != null) {
                reader.close(); // 必须手动关闭,且可能掩盖主异常
            }
        }
    }
    // 新方式的对比 - 更简洁
    public static void modernWay() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line = reader.readLine();
        } // 自动关闭
    }
}

网络资源管理

import java.io.*;
import java.net.Socket;
import java.net.URL;
public class NetworkResourceExample {
    // 管理网络连接
    public static void downloadContent(String urlString) {
        try (Socket socket = new Socket("example.com", 80);
             OutputStream os = socket.getOutputStream();
             InputStream is = socket.getInputStream()) {
            // 发送HTTP请求
            String request = "GET " + urlString + " HTTP/1.1\r\n" +
                           "Host: example.com\r\n" +
                           "Connection: close\r\n\r\n";
            os.write(request.getBytes());
            os.flush();
            // 读取响应
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, bytesRead));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

互斥锁资源

import java.util.concurrent.locks.ReentrantLock;
public class LockResourceExample {
    private static ReentrantLock lock = new ReentrantLock();
    // 自定义AutoCloseable的锁
    static class LockHelper implements AutoCloseable {
        public LockHelper() {
            lock.lock();
            System.out.println("获取锁");
        }
        @Override
        public void close() {
            lock.unlock();
            System.out.println("释放锁");
        }
    }
    public static void main(String[] args) {
        // 使用try-with-resources自动管理锁
        try (LockHelper helper = new LockHelper()) {
            System.out.println("执行临界区代码");
            // 业务逻辑...
        }
    }
}

结合Lambda表达式

import java.io.*;
import java.nio.file.*;
public class FunctionalExample {
    public static void processFile(String filePath) {
        // 更简洁的写法,支持链式操作
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.filter(line -> !line.startsWith("#"))  // 过滤注释
                 .map(String::trim)                        // 去除空格
                 .filter(line -> !line.isEmpty())          // 过滤空行
                 .forEach(System.out::println);            // 打印
        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
        }
    }
}

数据库连接管理(模拟)

import java.sql.*;
public class DatabaseExample {
    public static void queryUsers() {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";
        // JDBC 7+ 支持try-with-resources
        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
            while (rs.next()) {
                System.out.println("用户: " + rs.getString("name"));
            }
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
        }
    }
}

实际项目中的完整示例

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class RealWorldExample {
    public static class User {
        private String name;
        private String email;
        public User(String name, String email) {
            this.name = name;
            this.email = email;
        }
        @Override
        public String toString() {
            return "User{name='" + name + "', email='" + email + "'}";
        }
    }
    // 从CSV文件读取用户数据
    public static List<User> readUsersFromCsv(String filePath) {
        List<User> users = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(filePath), 
                    StandardCharsets.UTF_8))) {
            String line;
            boolean firstLine = true;
            while ((line = reader.readLine()) != null) {
                if (firstLine) { // 跳过表头
                    firstLine = false;
                    continue;
                }
                String[] parts = line.split(",");
                if (parts.length >= 2) {
                    users.add(new User(parts[0].trim(), parts[1].trim()));
                }
            }
        } catch (FileNotFoundException e) {
            System.err.println("文件不存在: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("读取文件错误: " + e.getMessage());
        }
        return users;
    }
    // 将用户数据写入JSON文件(简化版)
    public static void writeUsersToJson(List<User> users, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                    new FileOutputStream(filePath), 
                    StandardCharsets.UTF_8))) {
            writer.write("[");  
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                if (i > 0) writer.write(",");
                writer.write(String.format(
                    "\n  {\"name\": \"%s\", \"email\": \"%s\"}", 
                    user.name, user.email
                ));
            }
            writer.write("\n]");
            System.out.println("成功写入 " + users.size() + " 个用户到 " + filePath);
        } catch (IOException e) {
            System.err.println("写入文件错误: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        // 完整流程示例
        List<User> users = readUsersFromCsv("users.csv");
        users.forEach(System.out::println);
        writeUsersToJson(users, "users.json");
    }
}

高级技巧:封装资源管理

import java.io.*;
import java.util.function.Consumer;
public class ResourceWrapperExample {
    // 通用的资源处理器
    public static <T extends AutoCloseable> void withResource(
            ResourceFactory<T> factory,
            Consumer<T> consumer,
            String resourceName) {
        try (T resource = factory.create()) {
            consumer.accept(resource);
        } catch (Exception e) {
            System.err.printf("处理资源 '%s' 失败: %s%n", 
                resourceName, e.getMessage());
        }
    }
    @FunctionalInterface
    interface ResourceFactory<T> {
        T create() throws Exception;
    }
    static class TempFile implements AutoCloseable {
        public TempFile(String name) {
            System.out.println("创建临时文件: " + name);
        }
        public void write(String content) {
            System.out.println("写入内容: " + content);
        }
        @Override
        public void close() {
            System.out.println("删除临时文件");
        }
    }
    public static void main(String[] args) {
        // 使用通用处理器
        withResource(
            () -> new TempFile("temp.txt"),
            file -> file.write("测试内容"),
            "临时文件"
        );
    }
}
  1. 自动关闭:不用手动调用close()方法
  2. 多资源管理:可同时管理多个资源
  3. 异常处理:主异常不会被覆盖,额外异常作为抑制异常加入
  4. 简洁代码:减少finally块的使用
  5. 自定义资源:实现AutoCloseable接口即可
  6. 顺序保证:资源按声明顺序的逆序关闭

使用try-with-resources能让代码更安全、更简洁,是现代Java开发中的推荐实践!

上一篇Java泛型案例

下一篇当前分类已是最新一篇

抱歉,评论功能暂时关闭!