Java7新的try-with-resources语句,自动资源释放
来源:互联网 发布:苹果录屏软件 编辑:程序博客网 时间:2024/06/05 04:11
从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
新的语句支持包括流以及任何可关闭的资源,例如,一般我们会编写如下代码来释放资源:
private static void customBufferStreamCopy(File source, File target) { InputStream fis = null; OutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(target); byte[] buf = new byte[8192]; int i; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } } catch (Exception e) { e.printStackTrace(); } finally { close(fis); close(fos); }}private static void close(Closeable closable) { if (closable != null) { try { closable.close(); } catch (IOException e) { e.printStackTrace(); } }}
代码挺复杂的,异常的管理很麻烦。
而使用 try-with-resources 语句来简化代码如下:
private static void customBufferStreamCopy(File source, File target) { try (InputStream fis = new FileInputStream(source); OutputStream fos = new FileOutputStream(target)){ byte[] buf = new byte[8192]; int i; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } } catch (Exception e) { e.printStackTrace(); }}
代码清晰很多吧?在这个例子中,数据流会在 try 执行完毕后自动被关闭,前提是,这些
可关闭的资源必须实现 java.lang.AutoCloseable 接口。
转自:http://www.oschina.net/question/12_10706
0 0
- Java7新的try-with-resources语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放 try(){} catch(){}
- try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java 7 新的 try-with-resources 语句,自动资源释放
- Java7新特性--try-with-resources,自动关闭资源
- Java7提供了简化关闭资源的try语句:try-with-resources自动关闭资源的try语句
- java7新特性:Try - with - Resources语句
- Java7 新特性:try() 语句 即 try-with-resources
- 使用try-with-resources自动释放资源
- try-with-resources资源自动释放特性
- Java 7 try-with-resources 语句,自动资源释放,提高容错率!
- Java7新语法 -try-with-resources
- logstash-input-jdbc实现oracle 与elasticsearch实时同步详解
- TortoiseGit学习笔记
- Android常用的开源项目及其比较系列-Retrofit进阶教程
- 微信支付 h5
- Unbuntu 16.04LTS 安装sogou 输入法详解
- Java7新的try-with-resources语句,自动资源释放
- JDBC用法JAVA266-276
- SpringMVC与struts2区别和第一个springMVC应用
- Matlab绘制三维曲面
- sqlite错误处理:library routine called out of sequence
- 为什么Lisp语言如此先进?(译文)
- android高级第一天
- Unix发展史
- jaxp dom4j以及xpath常用api