众所周知,所有被打开的系统资源,比如流、文件、Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。
在JDK1.7以前,我们想要关闭资源就必须的finally代码块中完成。
【示例】JDK7之前资源的关闭的方式
/**
* 测试类
*/
public class Test {
public static void main(String[] args) throws IOException {
FileInputStream inputStream = null;
try {
// 创建字节输入流,注意:“file.txt”文件在项目中不存在,则会抛出异常
inputStream = new FileInputStream("file.txt");
// 执行存储数据的操作,此处省略。。。
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
// 关闭流
inputStream.close();
}
}
}
}
JDK7及以后关闭资源的正确姿势:try-with-resource,该语法格式:
try(/*需要关闭的资源*/){
// 容易出现异常的代码
}catch(Exception e) {
// 处理异常
}
Resource的定义:所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。
【示例】实现对try-with-resource的验证
/**
* 资源类
*/
class Resource implements AutoCloseable {
public void sayHello() {
System.out.println("hello");
}
@Override
public void close() throws Exception {
System.out.println("Resource is closed");
}
}
/**
* 测试类
*/
public class Test{
public static void main(String[] args) {
try(Resource resource = new Resource()) {
resource.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果为:
【示例】当存在多个打开资源的时候
/**
* 资源类
*/
class Resource1 implements AutoCloseable {
public void sayHello() {
System.out.println("Resource1 hello");
}
@Override
public void close() throws Exception {
System.out.println("Resource is closed");
}
}
class Resource2 implements AutoCloseable {
public void sayHello() {
System.out.println("Resource2 hello");
}
@Override
public void close() throws Exception {
System.out.println("Resource is closed");
}
}
/**
* 测试类
*/
public class Test{
public static void main(String[] args) {
try(Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {
r1.sayHello();
r2.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果为:
通过try-with-resource来释放资源,即使资源很多,代码也可以写的很简洁,如果用JDK1.7之前的方式去关闭资源,那么资源越多,用fianlly关闭资源时嵌套也就越多。
ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。