当前位置: 移动技术网 > IT编程>开发语言>Java > 如何在JDK 9中更简洁使用 try-with-resources 语句

如何在JDK 9中更简洁使用 try-with-resources 语句

2019年07月19日  | 移动技术网IT编程  | 我要评论

在 jdk 7 之前,资源需要手动关闭

例如下面一个很常见的文件操作的例子:

charset charset = charset.forname("us-ascii");
string s = ...;
bufferedwriter writer = null;
try {
writer = files.newbufferedwriter(file, charset);
writer.write(s, 0, s.length());
} catch (ioexception x) {
system.err.format("ioexception: %s%n", x);
} finally {
if (writer != null) writer.close();
}

在 jdk 7 之前,你一定要牢记在 finally 中执行 close 以释放资源

jdk 7 中的 try-with-resources 介绍

try-with-resources 是 jdk 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.autocloseable 接口(其中,它包括实现了 java.io.closeable 的所有对象),可以使用作为资源。

例如,我们自定义一个资源类

public class demo { 
public static void main(string[] args) {
try(resource res = new resource()) {
res.dosome();
} catch(exception ex) {
ex.printstacktrace();
}
}
}
class resource implements autocloseable {
void dosome() {
system.out.println("do something");
}
@override
public void close() throws exception {
system.out.println("resource is closed");
}
}

执行输出如下:

do something
resource is closed

可以看到,资源终止被自动关闭了。

再来看一个例子,是同时关闭多个资源的情况:

public class main2 { 
public static void main(string[] args) {
try(resourcesome some = new resourcesome();
resourceother other = new resourceother()) {
some.dosome();
other.doother();
} catch(exception ex) {
ex.printstacktrace();
}
}
}
class resourcesome implements autocloseable {
void dosome() {
system.out.println("do something");
}
@override
public void close() throws exception {
system.out.println("some resource is closed");
}
}
class resourceother implements autocloseable {
void doother() {
system.out.println("do other things");
}
@override
public void close() throws exception {
system.out.println("other resource is closed");
}
}

最终输出为:

do something
do other things
other resource is closed
some resource is closed

在 try 语句中越是最后使用的资源,越是最早被关闭。

try-with-resources 在 jdk 9 中的改进

作为 milling project coin 的一部分, try-with-resources 声明在 jdk 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

例如,给定资源的声明

// a final resource
final resource resource1 = new resource("resource1");
// an effectively final resource
resource resource2 = new resource("resource2");

老方法编写代码来管理这些资源是类似的:

// original try-with-resources statement from jdk 7 or 8
try (resource r1 = resource1;
resource r2 = resource2) {
// use of resource1 and resource 2 through r1 and r2.
}

而新方法可以是

// new and improved try-with-resources statement in jdk 9
try (resource1;
resource2) {
// use of resource1 and resource 2.
}

看上去简洁很多吧。对 java 未来的发展信心满满。

愿意尝试 jdk 9 这种新语言特性的可以下载使用 jdk 9 快照。enjoy!

源码

本章例子的源码,可以在 中 com.waylau.essentialjava.exception.trywithresources 包下找到。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网