1,什么是try-with-resources ?
- try-with-resources 是JDK 1.7 新增的语法糖
2,为什么使用try-with-resources ?
- 对于可关闭的资源的处理往往很复杂,使用 try-with-resources 语法可以简化代码,利于程序员的编写
例如:在JDK 1.7 之前,对于流我们需要这样操作:
package test2;
import java.io.*;
public class Test4 {
public static void main(String[] args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream("hwh.txt");
fis = new FileInputStream("hwh.txt");
byte[] buff = new byte[10];
int len;
while ((len=fis.read(buff)) != -1){
fos.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
可以看到,为了确保流能正常地关闭,我们对流的处理是非常的复杂的。 为了简化代码,在JDK 1.7 时提供了try-with-resources 语法,用法如下:
package test2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test5 {
public static void main(String[] args) {
try(FileOutputStream fos = new FileOutputStream("hwh.txt");
FileInputStream fis = new FileInputStream("hwh.txt")) {
byte[] buff = new byte[10];
int len;
while ((len=fis.read(buff)) != -1){
fos.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
可以看到,代码简洁了许多。
在使用try-with-resouces 时,需要将创建流资源的语句放到try后面的()中,编译器会自动对流资源进行关闭。
3,JDK 1.9 时对 try-with-resources 的优化
JDK 1.7 时try-with-resources 的缺点:
- 资源的创建语句必须写在try后面的()中,作用域为try代码块,无法在try-catch之前或之后使用。
在JDK 1.9 时,我们不需要将整个资源的创建语句放入到try后面的()中,只需要将资源对象放到try后面的()中即可。例如一个方法:
class Util{
static void handle(FileOutputStream fos,FileInputStream fis){
try(fos;fis) {
byte[] buff = new byte[10];
int len;
while ((len=fis.read(buff)) != -1){
fos.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4,try-with-resources 的使用要求
- try后面的()里面放的是需要关闭的资源,并不一定是流资源。资源对象所在的类需要直接或间接地实现Closeable或AutoCloseable接口。
- try后面的()里可以放一条资源创建语句或一个资源对象;如果需要放多个资源,用;隔开