Java中的Try with Resources语句介绍

本文介绍了Java 7引入的try-with-resources,它能在资源使用完后自动关闭回收,前提是资源实现AutoCloseable接口。文中说明了其使用方法,包括替代try-catch-finally、同时使用多资源、自定义资源等,还提及资源关闭顺序,最后介绍了Java 9中的改进。

1.介绍

从Java7诞生了try-with-resources,这家伙可以在资源使用完后实现自动关闭回收。想想我们之前打开一个文件或流对象用完咋整的,是不是finally语句块中手动close的。

当然这类可自动关闭的资源前提是必须实现了AutoCloseable接口。

2.如何使用?

拿PrintWriter对象举例,资源必须在try结构中声明和初始化:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

看下JDK1.8中PrintWriter的定义:

All Implemented Interfaces:

Closeable, Flushable, Appendable, AutoCloseable

3.使用try-with-resources替代try-catch-finally

Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}
  • 下面是try-resources
try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

4.同时使用多个资源

可以在一个try-with-resources块中用分号分隔以声明多个资源。例如:

try (Scanner scanner = new Scanner(new File("testRead.txt"));
    PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
    while (scanner.hasNext()) {
	writer.print(scanner.nextLine());
    }
}

5.自定义一个实现了AutoCloseable接口的资源

前提是要实现Closeable或AutoCloseable接口,同时重写close方法。例如:

public class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Closed MyResource");
    }
}

6.资源的关闭顺序是怎样的?

这里遵循的是:最先被定义/获取的资源最后被关闭。以下为例:

  • 资源1
public class AutoCloseableResourcesFirst implements AutoCloseable {

    public AutoCloseableResourcesFirst() {
        System.out.println("Constructor -> AutoCloseableResources_First");
    }

    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_First");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_First");
    }
}
  • 资源2
public class AutoCloseableResourcesSecond implements AutoCloseable {

    public AutoCloseableResourcesSecond() {
        System.out.println("Constructor -> AutoCloseableResources_Second");
    }

    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_Second");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_Second");
    }
}
  • 测试
private void orderOfClosingResources() throws Exception {
    try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
        AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {

        af.doSomething();
        as.doSomething();
    }
}

输出:

Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First

7.Java9中的改进

来到java9我们可以在try-with-resources块中使用final或effectively final变量:

final Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
try (scanner;writer) { 
    // omitted
}

如上,scanner变量声明为final,而writer变量没有显式声明final,但是很明显它在第一次赋值后并没有做其它改变,java8开始自动认为其为final变量。这一特性也就是effectively final。

<think>我们正在讨论Javatry-with-resources语句。根据提供的引用内容,我们可以总结出以下关键点:1.**目的**:try-with-resources用于自动管理资源,确保资源在使用后被正确关闭,避免了手动关闭资源可能导致的资源泄漏问题。2.**语法结构**:基本语法为:```javatry(ResourceTyperesource=newResourceType()){//使用资源的代码}catch(Exceptione){//异常处理}```3.**要求**:资源必须实现`AutoCloseable`接口(该接口只有一个`close()`方法)。4.**工作方式**:无论代码块是否正常完成或抛出异常,资源都会自动关闭。如果有多个资源,它们会按照声明的相反顺序关闭。5.**优点**:简化了资源管理代码,减少了错误(如忘记关闭资源)。现在,根据用户的问题“我想了解Javatry-with-resources的用法和特性”,我们将详细展开:###一、基本用法####1.单个资源管理```javapublicclassTryWithResourcesExample{publicstaticvoidmain(String[]args){try(FileInputStreamfis=newFileInputStream("example.txt")){//使用文件输入流读取数据intdata=fis.read();while(data!=-1){System.out.print((char)data);data=fis.read();}}catch(IOExceptione){e.printStackTrace();}}}```说明:无论是否发生异常,`FileInputStream`都会在`try`块结束后自动关闭。####2.多个资源管理```javatry(FileInputStreamfis=newFileInputStream("input.txt");FileOutputStreamfos=newFileOutputStream("output.txt")){//同时使用输入流和输出流(例如文件复制)byte[]buffer=newbyte[1024];intlength;while((length=fis.read(buffer))>0){fos.write(buffer,0,length);}}catch(IOExceptione){e.printStackTrace();}```注意:多个资源用分号分隔,关闭顺序与声明顺序相反(即先关闭`fos`,再关闭`fis`)。###二、工作原理在编译后,try-with-resources会被转换为传统的try-catch-finally结构,并在`finally`块中调用资源的`close()`方法。同时,它会处理异常抑制(SuppressedExceptions)的情况:-如果`try`块和`close()`方法都抛出异常,则`try`块的异常会被抛出,而`close()`方法的异常会被添加到主异常的被抑制异常列表中(通过`Throwable.addSuppressed()`)。###三、自定义资源任何实现了`AutoCloseable`接口的类都可以作为资源。例如:```javapublicclassCustomResourceimplementsAutoCloseable{publicvoiddoSomething(){System.out.println("执行操作...");}@Overridepublicvoidclose(){System.out.println("资源已被关闭");}}//使用try(CustomResourcecr=newCustomResource()){cr.doSomething();}//无需显式调用close()```###四、特性与注意事项1.**资源变量是隐式final的**:不能在try块中重新赋值。```javatry(Resourcer=newResource()){r=null;//编译错误}```2.**资源声明可以包含变量初始化,但不能调用可能抛出非受检异常的方法**(除了构造函数)。3.**JDK9的改进**:支持在try外部声明资源变量,但要求变量是final或等效final的。```javaResourcer1=newResource();//等效finaltry(r1){...}```4.**异常处理**:-如果`try`块和资源关闭都抛出异常,原始异常(即`try`块中的异常)被抛出,而关闭时的异常通过`Throwable.getSuppressed()`获取。-可以捕获多个异常,但要注意异常类型。###五、与传统try-finally对比**传统方式**:```javaResourceresource=null;try{resource=newResource();//使用资源}catch(Exceptione){//异常处理}finally{if(resource!=null){try{resource.close();}catch(Exceptione){//关闭异常处理}}}```缺点:代码冗长,嵌套层级深,容易遗漏关闭。**try-with-resources**:代码简洁,自动管理。###常见问题示例**Q:如何访问被抑制的异常?**```javatry(Resourcer=newResource()){//可能抛出异常的操作}catch(Exceptione){//主异常Throwable[]suppressed=e.getSuppressed();//处理被抑制的异常}```**Q:JDBC资源如何用try-with-resources管理?**```javatry(Connectionconn=DriverManager.getConnection(url);PreparedStatementps=conn.prepareStatement(sql);ResultSetrs=ps.executeQuery()){while(rs.next()){//处理结果}}catch(SQLExceptione){//处理异常}```**Q:资源关闭顺序是?**答:按声明顺序的相反顺序关闭(后声明先关闭)。###总结try-with-resourcesJava7引入的关键特性,极大简化了资源管理代码。其核心是资源自动关闭机制,适用于所有实现了`AutoCloseable`接口的资源类型。§§相关问题§§1.为什么资源需要实现`AutoCloseable`接口?它与`Closeable`有什么区别?2.在try-with-resources中如何处理多个异常的捕获?3.JDK9对try-with-resources做了哪些增强?4.如何自定义一个可用于try-with-resources的资源类?5.如果资源关闭方法抛出异常,会如何影响程序流程?</think> ### Java try-with-resources 详解 `try-with-resources` 是 Java 7 引入的**自动资源管理语法**,用于简化资源(如文件流、数据库连接、网络套接字等)的关闭操作,避免资源泄漏。其核心原理是通过 `AutoCloseable` 接口自动调用资源的 `close()` 方法[^1][^2][^3]。 --- #### 一、核心特性 1. **自动关闭** 资源在 `try` 块结束时**自动调用 `close()` 方法**,无需手动编写 `finally` 块。 ```java try (Resource resource = new Resource()) { // 自动关闭 resource.use(); } catch (Exception e) { e.printStackTrace(); } ``` 2. **异常处理优先级** - 如果 `try` 块和 `close()` **同时抛出异常**,`try` 块的异常为主异常,`close()` 的异常通过 `Throwable.getSuppressed()` 获取[^1]。 - 资源关闭异常**不会掩盖业务逻辑异常**。 3. **资源声明顺序** 多个资源按**声明顺序的逆序关闭**(后声明的先关闭): ```java try (FileInputStream fis = new FileInputStream("in.txt"); FileOutputStream fos = new FileOutputStream("out.txt")) { // 使用资源(fos 先关闭,fis 后关闭) } ``` --- #### 二、使用条件 - 资源类必须实现 **`AutoCloseable`** 接口(或子接口 `Closeable`): ```java public class Resource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("资源已关闭"); } } ``` --- #### 三、代码示例 1. **基本用法(文件流)** ```java try (FileInputStream fis = new FileInputStream("data.txt")) { int data; while ((data = fis.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { System.err.println("文件操作异常:" + e.getMessage()); } // 自动调用 fis.close() ``` 2. **多资源管理(JDBC 连接)** ```java try (Connection conn = DriverManager.getConnection(url); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { System.out.println(rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } // 自动关闭顺序:rs → ps → conn ``` 3. **自定义资源类** ```java class Light implements AutoCloseable { void turnOn() { System.out.println("灯光开启"); } @Override public void close() { System.out.println("灯光关闭"); } } try (Light light = new Light()) { light.turnOn(); } // 输出:灯光开启 → 灯光关闭 ``` --- #### 四、与传统写法的对比 | **特性** | try-with-resources | 传统 try-finally | |------------------|--------------------------|--------------------------| | **代码量** | 减少 30%-50% | 冗余 | | **异常处理** | 支持异常抑制(JDK7+) | 可能掩盖主异常 | | **资源泄漏风险** | 无 | 可能因忘记关闭导致泄漏 | | **可读性** | ⭐⭐⭐⭐⭐ | ⭐⭐ | > **传统写法对比**: > ```java > // 传统写法(易漏关资源) > FileInputStream fis = null; > try { > fis = new FileInputStream("data.txt"); > // 使用资源 > } finally { > if (fis != null) fis.close(); // 需手动检查 null > } > ``` --- #### 五、进阶技巧(JDK 9+) 1. **重用已声明资源** ```java Resource res1 = new Resource(); // 等效 final try (res1) { // JDK9+ 支持外部变量 res1.use(); } ``` 2. **嵌套资源管理** ```java try (ZipFile zip = new ZipFile("data.zip"); InputStream is = zip.getInputStream(zip.getEntry("file.txt"))) { // 读取压缩包内文件 } ``` --- #### 常见问题 **Q1:资源关闭失败会怎样?** A:抛出 `IOException` 或实现类自定义异常(可通过 `Throwable.getSuppressed()` 获取[^1])。 **Q2:哪些Java类原生支持?** A:所有标准 I/O 类(如 `FileInputStream`、`Socket`)、JDBC 接口(`Connection`, `Statement`)、NIO `Channel` 等[^4]。 **Q3:能用于非资源类吗?** A:不能,类必须实现 `AutoCloseable`(否则编译报错)。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值