java7简化资源清理(try-with-resources)自动关闭资源的try语句,try-with-resources 是一个定义了一个或多个资源的try 声明,这个资源是指程序处理完它之后需要关闭它的对象。try-with-resources 确保每一个资源在处理完成后都会被关闭。 可以使用try-with-resources的资源必须实现java.lang.AutoCloseable 接口。
结构代码:
try
(
//这里写关闭资源的对象,且实现了java.lang.AutoCloseable 接口
)
{
}catch (Exception e){
}
实例代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class AutoCloseDemo {
public void copy(File src, File dest) {
if (src == null || dest == null) {
return;
}
try (
InputStream in = new FileInputStream(src);
OutputStream os = new FileOutputStream(dest);
) {
//定义一个字节数组
byte[] buf = new byte[1024];
//定义一个int类型变量,用于记录读入到字节数组的总字节数
int len = 0;
while((len = in.read(buf))!= -1){
os.write(buf, 0, len);
}
} catch (IOException e) {
//出来异常的代码
e.printStackTrace();
}
}
}