Java 7简化资源清理(try-with-resources)自动关闭资源的try语句
自动关闭资源格式:
try( )//此处多了圆括号,()圆括号内写打开资源的代码,在这里创建的对象必须实现Autocloseable接口
{
IO操作
}
catch(){
处理异常的代码
}
Eg:package july7file;
//java7开始的自动关闭资源
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Demo8 {
public static void main(String[] args) throws IOException {
File src = new File("E:/自荐信.doc");
File tar = new File("E:/自荐信1.doc");
copy(src, tar);
System.out.println("Well done !");
}
public static void copy(File src, File tar) throws IOException {
try (InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(tar);) //圆括号内写打开资源的操作
{
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
os.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}