Java try-with-resources 怎么用?最佳入门示例

Java的try-with-resources是专为AutoCloseable接口设计的语法糖,资源声明在try括号内,JVM保证自动关闭(含异常时),支持多资源逆序关闭、抑制异常及自定义资源实现。

Java 的 try-with-resources 是自动关闭资源的语法糖,专为实现 AutoCloseable 接口的对象设计,避免手动写 finally 关闭,减少资源泄漏风险。核心就一点:把资源声明在 try 括号里,JVM 保证它用完立刻关闭(哪怕抛异常)。

基础写法:一个资源最简示例

比如读文件,以前要这样写:

// 容易漏掉 close 或异常时没执行到
FileInputStream fis = null;
try {
    fis = new FileInputStream("data.txt");
    // 处理数据...
} finally {
    if (fis != null) fis.close();
}

现在一行搞定:

try (FileInputStream fis = new FileInputStream("data.txt")) {
    // 处理数据...
    // fis 会自动关闭,不用管
}

只要 FileInputStream 实现了 AutoCloseable(它确实实现了),就能这么用。

多个资源:逗号分隔,按声明逆序关闭

常见场景是“读文件 → 解析 → 写结果”,涉及输入流、输出流、缓冲器等:

try (
    FileInputStream fis = new FileInputStream("input.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
    FileOutputStream fos = new FileOutputStream("output.txt");
    PrintWriter writer = new PrintWriter(fos)
) {
    String line;
    while ((line = reader.readLine()) != null) {
        writer.println(line.toUpperCase());
    }
} // ← 这里自动关闭:writer → fos → reader → fis(逆序)

注意点:

  • 每个资源独占一行,加分号
  • 关闭顺序是“后声明的先关”,确保依赖关系安全(比如 PrintWriter 依赖 FileOutputStream,所以先关 writer)
  • 任一资源构造失败,已成功创建的会自动关闭

异常处理:原有异常不被吞,支持抑制异常

如果 try 块里抛异常,同时资源关闭也抛异常(比如写入未 flush 就关流),JVM 会把关闭异常“抑制”(suppressed),主异常仍被抛出,关闭异常可查:

try (FileInputStream fis = new FileInputStream("missing.txt")) {
    // 文件不存在 → 抛 FileNotFoundException
} catch (IOException e) {
    System.out.println("主异常: " + e.getMessage());
    for (Throwable suppressed : e.getSuppressed()) {
        System.out.println("被抑制的异常: " + suppressed);
    }
}

这样既不丢原始错误,也不掩盖关闭问题。

自定义资源:让自己的类支持 try-with-resources

只需实现 AutoCloseable 接口,重写 close() 方法:

class MyResource implements AutoCloseable {
    public void doSomething() {
        System.out.println("正在操作...");
    }

    @Override
    public void close() {
        System.out.println("已清理并关闭");
    }
}

// 使用
try (MyResource res = new MyResource()) {
    res.doSomething();
} // ← 自动调用 close()

适合封装数据库连接、网络 socket、锁、临时文件等需要显式释放的资源。

基本上就这些。记住三要素:资源类型必须实现 AutoCloseable、声明在 try 后括号中、不用手动 close。写起来干净,逻辑更可靠。