Java 7新特性:自动化资源管理

在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();
     }
   }
}

在操作完成后,我们需要手动调用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();
}

我们将需要自动关闭的资源放在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();
      }
   }
}

运行结果:

process...
close...

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值