Java 7 新的 try-with-resources 语句,自动资源释放

来源:互联网 发布:黑马手机安全卫士源码 编辑:程序博客网 时间:2024/06/05 04:13

从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

新的语句支持包括流以及任何可关闭的资源,例如,一般我们会编写如下代码来释放资源:

?

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private static void customBufferStreamCopy(File source, File target) {  
  2.     InputStream fis = null;  
  3.     OutputStream fos = null;  
  4.     try {  
  5.         fis = new FileInputStream(source);  
  6.         fos = new FileOutputStream(target);  
  7.     
  8.         byte[] buf = new byte[8192];  
  9.     
  10.         int i;  
  11.         while ((i = fis.read(buf)) != -1) {  
  12.             fos.write(buf, 0, i);  
  13.         }  
  14.     }  
  15.     catch (Exception e) {  
  16.         e.printStackTrace();  
  17.     } finally {  
  18.         close(fis);  
  19.         close(fos);  
  20.     }  
  21. }  
  22.     
  23. private static void close(Closeable closable) {  
  24.     if (closable != null) {  
  25.         try {  
  26.             closable.close();  
  27.         } catch (IOException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.     }  
  31. }  


代码挺复杂的,异常的管理很麻烦。

而使用 try-with-resources 语句来简化代码如下:在try中初始化, try 执行完毕后自动被关闭

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 接口。

0 0
原创粉丝点击