Try-with-resources是Java7中一个新的异常处理机制,它能够很容易地关闭在try-catch语句块中使用的资源。 在Java7以前,程序中使用的资源需要被明确地关闭,通常是在finally语句块里释放资源。
1.如何使用try-with-resources
例如:
public class FileOutputStreamDemo {
public static void main(String[] args) {
File srcFile = new File("d:" + File.separator + "html_logo.jpg");
File dest = new File("d:" + File.separator + "dest.jpg");
InputStream fin=null;
OutputStream fout=null;
try {
fin = new FileInputStream(srcFile);
fout = new FileOutputStream(dest);
long startTime = System.currentTimeMillis();
//一边读,一边写
int data=-1;
while((data= fin.read())!=-1){
fout.write(data);
}
long endTime = System.currentTimeMillis();
System.out.println("总用时:"+(endTime - startTime)+"毫秒");
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(fin!=null){
try {
fin.close();
fin=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(fout!=null){
try {
fout.close();
fout=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
不论try语句块中是否有异常抛出,finally语句块始终会被执行。这意味着,不论try语句块中发生什么,InputStream 都会被关闭,或者说都会试图被关闭。如果关闭失败,InputStream’s close()方法也可能会抛出异常。所以必须在finally里再包裹一层try-catch捕获异常,这样给用户的体验有点繁琐。
在Java7后,对于上面的例子可以用try-with-resource 结构这样写:
public class FileOutputStreamDemo {
public static void main(String[] args) {
File srcFile = new File("d:" + File.separator + "html_logo.jpg");
File dest = new File("d:" + File.separator + "dest.jpg");
try (InputStream fin = new FileInputStream(srcFile); OutputStream fout = new FileOutputStream(dest);) {
long startTime = System.currentTimeMillis();
//一边读,一边写
int data = -1;
while ((data = fin.read()) != -1) {
fout.write(data);
}
long endTime = System.currentTimeMillis();
System.out.println("总用时:" + (endTime - startTime) + "毫秒");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
这样看上去,代码简洁很多。 注意:try后面的小括号里声明的变量类型必须是实现了AutoCloseable接口。这里的InputStream和OutputStream都实现了AutoCloseable接口。
2.使用try-with-resources注意事项