19

java9系列第二篇-资源自动关闭的语法增强

 3 years ago
source link: http://www.cnblogs.com/zimug/p/13818458.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

UnYRjyz.png!mobile

我计划在后续的一段时间内,写一系列关于java 9的文章,虽然java 9 不像Java 8或者Java 11那样的核心java版本,但是还是有很多的特性值得关注。期待您能关注我,我将把java 9 写成一系列的文章,大概十篇左右。

在Java 9的版本中,对从JDK 7开始支持的try-with-resources语法进行了改进。虽然只是一个小小的改进,我仍希望把他介绍给你,我们一起来每天进步一点点。

一、先说Java7的try-with-resources(Java9改进版在后文)

在Java 7之前没有 try-with-resources 语法,所有的流的销毁动作,全都需要自己在finally方法中手动的写代码进行关闭。如下文中的代码,将一个字符串写入到一个文件里面。

@Test
void testStream() throws IOException {
  String fileName = "D:\\data\\test\\testStream.txt";

  FileOutputStream fos = new FileOutputStream(fileName);  //创建IO管道流
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  BufferedWriter bw = new BufferedWriter(osw);

  try{
    bw.write("手写代码进行Stream流的关闭");
    bw.flush();
  }finally{
    bw.close();   //手动关闭IO管道流
    osw.close();
    fos.close();
  }
}

从Java 7版本开始提供了 try-with-resources 语法,我们只需要把管道流用 try() 包含起来,在try代码段执行完成之后,IO管道流就会自动的关闭,不需要我们手写代码去关闭,这很简洁!

@Test
void testTry() throws IOException {
  String fileName = "D:\\data\\test\\testTry.txt";
  try(FileOutputStream fos = new FileOutputStream(fileName);
      OutputStreamWriter osw = new OutputStreamWriter(fos);
      BufferedWriter bw = new BufferedWriter(osw);){
    bw.write("IO管道流被自动调用close()方法");
    bw.flush();
  }
}

二、避免走入误区

很多小伙伴在知道 try-with-resources 语法之后,容易陷入误区

try-with-resources

误区一把实践范围缩小了,而误区二把实践范围夸大了。 那么什么样的资源可以被自动关闭呢?答案就是实现了AutoCloseable或Closeable接口的类可以自动的进行资源关闭。

public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}

Closeable接口继承自AutoCloseable接口,二者都包含close()方法。如果你自定义的占用系统资源的类需要进行资源回收,请实现这两个接口之一,并在close()方法中进行资源回收与关闭。这样你自定义的类,也可以使用 try-with-resources 语法进行资源回收与关闭。

三、 try-with-resources 在Java 9中的改进

try-with-resources 语法在java 9 中进行了改进, try-with-resources 语法的 try() 可以包含变量,多个变量用分号隔开。

这样的改进目的是让语义更加明确,将资源创建代码与尝试资源回收的语法分离。

try()
@Test
void testJava9Try() throws IOException {
  String fileName = "D:\\data\\test\\testJava9Try.txt";

  FileOutputStream fos = new FileOutputStream(fileName);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  BufferedWriter bw = new BufferedWriter(osw);

  try(bw;osw;fos){  //注意这里:尝试去回收这三个对象对应的资源,和上文中的java 7代码对比
    bw.write("Java9-可以被自动调用close()方法");
    bw.flush();
  }
}

欢迎关注我的博客,里面有很多精品合集

  • 本文转载注明出处(必须带连接,不能只转文字): 字母哥博客

觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力!。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK