一、介绍
jdk7开始比try-fianlly更简单的资源释放方案,try-finally代码臃肿,不太优雅。于是有了更加优雅的try-with
-resource。
二、使用样式
在try后面写一对小括号,将你要用到的资源比如流对象写进里面,当你使用完流对象的时候,它会自动帮你释放资源(该资源使用完毕后,会自动调用其close()方法,完成对资源的释放!)
三、代码演示
package com.yucako.d4_tryFinally;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class tryRe3 {
public static void main(String[] args) {
try (
FileInputStream is = new FileInputStream("D:jj/kk");
FileOutputStream os = new FileOutputStream("D:dd/kk");
//注意事项:只能写资源对象(流对象)
//什么时流对象:实现了AutoCloseable接口;资源对象里面都有close方法
){
byte [] bytes = new byte[1024];
int len ;
while ((len=is.read())!=-1){
os.write(bytes,0,len);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
测试:是否会自动运行close
package com.yucako.d4_tryFinally;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class tryRe3 {
public static void main(String[] args) {
try (
// FileInputStream is = new FileInputStream("D:jj/kk");
// FileOutputStream os = new FileOutputStream("D:dd/kk");
//注意事项:只能写资源对象(流对象)
//什么时流对象:实现了AutoCloseable接口;资源对象里面都有close方法
MyClose mm = new MyClose();//测试流对象是否自动运行 close
){
// byte [] bytes = new byte[1024];
// int len ;
// while ((len=is.read())!=-1){
// os.write(bytes,0,len);
// }
System.out.println(mm);//测试流对象是否自动运行 close
}catch (Exception e){
e.printStackTrace();
}
}
}
package com.yucako.d4_tryFinally;
public class MyClose implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("关闭了与某个硬盘的连接");
}
}
结果: