天下脸皮共十分
我占八分

流关闭

JDK9的改进(扩展知识点了解内容)

JDK9中try-with-resource 的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,同样可以自动关闭,无需手动close,我们来了解一下格式。

改进前格式:

// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");
// 引入方式:创建新的变量保存
try (Resource r1 = resource1;
    Resource r2 = resource2) {
    // 使用对象
}

改进后格式:

// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");

// 引入方式:直接引入
try (resource1; resource2) {
    // 使用对象
}

改进后,代码使用演示:

public class TryDemo {
   public static void main(String[] args) throws IOException {
      // 创建流对象
       final  FileReader fr  = new FileReader("in.txt");
       FileWriter fw = new FileWriter("out.txt");
      // 引入到try中
       try (fr; fw) {
        // 定义变量
           int b;
        // 读取数据
        while ((b = fr.read())!=-1) {
          // 写出数据
          fw.write(b);
        }
      } catch (IOException e) {
           e.printStackTrace();
      }
  }
}
赞(1) 打赏
未经允许不得转载:Stephen Young » 流关闭
分享到: 更多 (0)

评论 1

评论前必须登录!

 

  1. #1

    Genius

    stephen 5年前 (2020-07-02) 这家伙可能用了美佬的代理 谷歌浏览器 Windows 10

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏