java7新特性--自动关闭资源
来源:互联网 发布:js 提示允许加载flash 编辑:程序博客网 时间:2024/06/05 17:39
格式
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 }}
0 0
- java7新特性之一自动关闭资源
- java7新特性--自动关闭资源
- 黑马程序员----java7新特性之自动关闭资源
- Java7新特性--try-with-resources,自动关闭资源
- Closeable和java7自动资源释放特性
- 在Java7中使用try语句自动关闭资源
- java7.的新特性!
- Java7新特性
- java7 新特性
- java7 新特性
- Java7新特性
- java7 新特性
- java7新特性(1)
- java7新特性
- JAVA7新特性
- Java7语法新特性
- java7 语法新特性
- Java7新特性
- SpringMVC处理异常
- SendMessage函数
- linux dd命令
- 分布式事务控制分段提交
- ubuntu storm安装配置
- java7新特性--自动关闭资源
- MJPG_Streamer的安装及使用
- linux中内存使用,swap,cache,buffer的含义总结
- HTTP协议学习笔记
- 自定义控件之DrawerLayout实现侧滑
- 国际C混乱码大赛
- Android问题集锦之四十九:Can't add XStream file dependency to Android Studio project
- Android Studio 开发使用总结
- POJ 2387 Til the Cows Come Home (Dijkstra)