专栏名称: Java专栏
一个Java、Python、数据库、中间件、业内资讯、面试、学习资源等干货的知识分享社区。
目录
相关文章推荐
知识星球精选  ·  全网最好用的数据分析工具箱,限时优惠加入! ·  昨天  
甘肃省司法厅  ·  【促进民营经济高质量发展】政策加速落地显效 ... ·  2 天前  
文旅湖南  ·  今日春分|湖南人的餐桌上少不了这些春味 ·  2 天前  
51好读  ›  专栏  ›  Java专栏

你还在使用 try-catch-finally 关闭资源?不太优雅~

Java专栏  · 公众号  ·  · 2021-01-09 12:20

正文


作者: 何甜甜在吗

链接: https://juejin.im/post/5b8f9fa05188255c6f1df755


代码一定得写的优雅一点!

你还在使用try-catch-finally关闭资源吗,如果是,那么就有点out了。皮皮甜手把手教你使用 JDK7 引用的try-with-resource

JDK7之前资源的关闭姿势:

/**
* jdk7以前关闭流的方式
*
* @author hetiantian
* */
public class CloseResourceBefore7 {
private static final String FileName = "file.txt";

public static void main(String[] args) throws IOException {
FileInputStream inputStream = null;

try {
inputStream = new FileInputStream(FileName);
char c1 = (char) inputStream.read();
System.out.println("c1=" + c1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}

JDK7及以后关闭资源的正确姿势

try-with-resource Resource的定义:

所有实现了 java.lang.AutoCloseable [1] 接口(其中,它包括实现了 java.io.Closeable [2] 的所有对象),可以使用作为资源。简单Demo进行证实:实现java.lang.AutoCloseable接口的Resource类:

/**
* 资源类
*
* @author hetiantian
* */
public class Resource implements AutoCloseable {
public void sayHello() {
System.out.println("hello");
}

@Override
public void close() throws Exception {
System.out.println("Resource is closed");
}
}

测试类CloseResourceIn7.java

/**
* jdk7及以后关闭流的方式
*
* @author hetiantian
* */
public class CloseResourceIn7 {
public static void main(String[] args) {
try(Resource resource = new Resource()) {
resource.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
}
}

打印结果:

hello
Resource is closed

当存在多个打开资源的时候:资源二Resource2.java

/**
* 资源2
*
* @author hetiantian
* */
public class Resource2 implements AutoCloseable {
public void sayhello() {
System.out.println("Resource say hello");
}

@Override
public void close() throws Exception {
System.out.println("Resource2 is closed");
}
}

测试类CloseResourceIn7.java

/**
* jdk7及以后关闭流的方式
*
* @author hetiantian
* */
public class CloseResourceIn7 {
public static void main(String[] args) {
try(Resource resource = new Resource(); Resource2 resource2 = new Resource2()) {
resource.sayHello();
resource2.sayhello();
} catch (Exception e) {
e.printStackTrace();
}
}
}

打印结果:

hello
Resource say hello
Resource2 is closed
Resource is closed

即使资源很多,代码也可以写的很简洁,如果用 JDK7 之前的方式去关闭资源,那么资源越多,用fianl关闭资源时嵌套也就越多。

那么它的底层原理又是怎样的呢,由皮皮甜独家揭秘优雅关闭资源背后的密码秘密

查看编译的class文件CloseResourceIn7.class:







请到「今天看啥」查看全文