每天一分钟来一颗Java语法糖(五)try-with-resource
Java语法糖try-with-resource
try-with-resource引入版本
- Java1.7增加了新特性:try-with-resource,资源必须定义在try中,若已经在外面定义,则需要一个本地变量。
- Java1.9 不再要求定义临时变量,可以直接使用外部资源变量。
try-with-resource介绍
程序如果打开外部资源,在使用后需要正确的关闭。Java提供了try-catch-finally机制,未异常等问题提供了保证。Java1.7以后提供了try-with-resource,它比try-catch-finall简便。
try-with-resource注意事项
- 资源对象必须实现AutoCloseable接口,即实现close方法
如FileInputStream
try-with-resource演示
/**
* 使用try-catch-finally方式的复制文件
* @param source
* @param target
*/
public static void copy(String source, String target) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(target);
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 使用try-with-resource方式的复制文件
* @param source
* @param target
*/
public static void copy(String source, String target) {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用try-with-resource方式的复制文件,当然也可以不处理异常,异常让调用者自行处理
* @param source
* @param target
*/
public static void copy(String source, String target) throws IOException {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
}
}
使用try-with-resource后,代码简洁,可读性增强,同时也不用在想着怎么手动关闭资源文件,有时候这些资源文件不关闭,搞不好就是一个线上事故。
try-with-resource其实是语法糖
try-with-resource其实是语法糖,它将在编译时编译成关闭资源的代码。
把刚才try-with-resource编译后的class文件反编译后如下
public static void copy(String source, String target) {
try {
InputStream in = new FileInputStream(source);
Throwable var3 = null;
try {
OutputStream out = new FileOutputStream(target);
Throwable var5 = null;
try {
byte[] buff = new byte[1024];
int n;
while((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (Throwable var31) {
var5 = var31;
throw var31;
} finally {
if (out != null) {
if (var5 != null) {
try {
out.close();
} catch (Throwable var30) {
var5.addSuppressed(var30);
}
} else {
out.close();
}
}
}
} catch (Throwable var33) {
var3 = var33;
throw var33;
} finally {
if (in != null) {
if (var3 != null) {
try {
in.close();
} catch (Throwable var29) {
var3.addSuppressed(var29);
}
} else {
in.close();
}
}
}
} catch (IOException var35) {
var35.printStackTrace();
}
}