第四十四篇:Java 7新特性:自动化资源管理

来源:互联网 发布:视频会议软件好? 编辑:程序博客网 时间:2024/05/17 03:54

在JAVA7中为我们提供了一些很方便的新特性,如自动资源管理、数字字面量下划线支持、switch中使用string等,今天介绍一下自动资源管理。

Java中某些资源是需要手动关闭的,如InputStream,Writes,Sockets,Sql classes等。自动资源管理允许try语句本身申请更多的资源,这些资源作用于try代码块,并自动关闭。

首先我们来看一下传统的读取文件的方法:

BufferedReader reader = null;try{   reader = new BufferedReader(new FileReader("data.txt"));   String line = null;   while ((line = reader.readLine()) != null)   {      System.out.println(line);   }}catch (IOException e){   e.printStackTrace();}finally{   if (reader != null)   {      try      {         reader.close();      }      catch (IOException e)      {         e.printStackTrace();     }   }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

在操作完成后,我们需要手动调用close()方法,释放资源,在JAVA7中,我们只需要这样写:

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))){   String line = null;   while ((line = reader.readLine()) != null)   {      System.out.println(line);   }}catch (IOException e){   e.printStackTrace();}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

我们将需要自动关闭的资源放在try块中,是不是比传统的方法要简洁呢。到这里,我们不禁要问,这样写真的会释放资源吗?答案是肯定的,我们可以来测试一下,编写一个测试类,实现Closeable接口即可,

import java.io.Closeable;import java.io.IOException;public class AutoCloseTest implements Closeable{   @Override   public void close() throws IOException   {      System.out.println("close...");   }   public static void main(String[] args)   {      try (AutoCloseTest test = new AutoCloseTest())      {         System.out.println("process...");      }      catch (IOException e)      {         e.printStackTrace();      }   }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

运行结果:

process...close...
  • 1
  • 2
  • 1
  • 2

通过运行结果我们可以发现,我们虽然没有调用close()方法,但在try块执行完毕后会自动调用。这里面实现Closeable接口并不是很贴切,应该是实现AutoCloseable接口的实现类在try块中申请资源后就会自动释放,Closeable本质上也实现了AutoCloseable接口。

原创粉丝点击