格式
try(
//此处写打开资源的代码,此处创建的对象必须实现java.lang.AutoClosable接口
声明变量 变量=java.lang.AutoClosable接口的实例
)
{
}
catch{
//处理异常的方法
}
例:在java6中
public static void copy(File srcFile,File targetFile) {
if (srcFile==null||targetFile==null) {
System.out.println("文件为null");
return;
}
InputStream in=null;
OutputStream out=null;
try {
in=new FileInputStream(srcFile);
out=new FileOutputStream(targetFile);
byte[] b=new byte[1024];
int len=0;
while((len=in.read(b))!=-1){
//取出缓存区数据,取出后立马将数据写到另一个文件
out.write(b, 0, len);//读多少,写多少
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//throw new Exception(srcFile.getAbsolutePath()+"找不到");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (out!=null) {
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
//无论out是否关闭,都应关闭in
if (in!=null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
在java7中:
public static void copyByjava7(File srcFile,File targetFile){
try
( InputStream in=new FileInputStream(srcFile);
OutputStream out=new FileOutputStream(targetFile);
//The resource type Date does not implement java.lang.AutoCloseable
//即此处只能放实现了AutoCloseable接口的方法
//Date date=new Date();
)
{
byte[] b=new byte[1024];
int len=0;
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
} catch (Exception e) {
// TODO: handle exception
}
}
转载:https://blog.csdn.net/qq_32667757/article/details/51638416