代码一定得写的优雅一点!
你还在使用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: