——- android培训、java培训、期待与您交流! ———-
java.lang.Interface AutoCloseable Since: 1.7
自动关闭资源接口,Closeable的一个父接口,所有实现Closeable的类都可以自动关闭。
使用方法
try ( /*这儿写打开资源的代码,声明变量也必须放在此处,此处创建的对象
必须实现AutoCloseable接口,否则编译不通过,结尾圆括号后不能
写代码*/
)
{
/*在此处进行资源调用*/
} catch (IOException e) {
//处理异常的代码
}
示例代码
文件拷贝
public static void main(String[] args) {
try(//将打开资源的代码卸载try后面的小括号中
InputStream is=new FileInputStream("C:/文件夹/1280.jpg");
OutputStream os=new FileOutputStream("C:/1280.jpg");
){//在小括号后的大括号中使用打开的资源,使用完后,虚拟机会帮助自动关闭前面打开的资源
byte[] b = new byte[1024];
while(-1!=is.read(b)){
os.write(b);}
}catch (IOException e) {
}
对比代码
手动关闭资源
InputStream in = null;
OutputStream out = null;
try {
n = new FileInputStream("SrcFileName");
out = new FileOutputStream("TarFileName");
byte[] buff = new byte[1024];
while ((in.read(buff)) != -1) {
out.write(buff);// 读多少,同时就往外写多少
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {必须执行的代码,一定要关闭out流
try {
if (out != null) {//关闭之前要判断out不为空,否则会报错
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {// finnaly嵌套,无论out是否关闭,都应该关闭in
try {
if (in != null) {//关闭之前要判断in流不为空,否则会报错
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用自动关闭资源可以免除繁琐的手动关闭资源一级可能带来的异常,省时省力。