JDK1.7之后关闭资源的方式

在jdk1.7之前,我们遇到需要进行异常处理有需要进行关闭资源处理的时候会比较难受,因为每一个资源关闭的时候还需要进行非空判断,额外还需要进行单独的try-catch

我们来看一段复制图片的代码:

@Test
public void copyImage() {
  FileInputStream fis = null;
  FileOutputStream fos = null;
  try {
    fis = new FileInputStream("/Users/farajmujey/Documents/pictures/material/avatar/WechatIMG4943.jpeg");
    fos = new FileOutputStream("src/img.jpeg");
    byte[] target = new byte[1024];
    int len = 0;
    while ((len = fis.read(target)) != -1) {
      fos.write(target, 0, len);
    }
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    try {
      if (fos != null) {
        fos.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      if (fis != null) {
        fis.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

我们开了一个输入流,一个输出流,就需要进行两次资源的关闭操作,这样的代码看着又乱,有冗余。但是若资源不关闭则会造成资源的浪费。

在jdk1.7之后,Java为我们提供了一种try-with-resources的写法,可以让我们快速地完成资源的关闭操作。

{% p red, 语法 %}

try (
	[resources...]
) {
  [trybody....]
} catch(){}

使用这种方法上面的代码就可以简化成:

@Test
public void copyImage2() {
  try (
    InputStream fis = new FileInputStream("/Users/farajmujey/Documents/pictures/material/avatar/WechatIMG4943.jpeg");
    OutputStream fos = new FileOutputStream("src/img.jpeg")
  ) {
    byte[] target = new byte[1024];
    int len = 0;
    while ((len = fis.read(target)) != -1) {
      fos.write(target, 0, len);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

()中的资源,必须是常量,但是因为这和我们正常使用的代码是一样的所以可以不用大写。资源代码的最后需要加上;但如果是最后一个资源对象,末尾可以不加;

posted @ 2021-01-29 11:43  FarajMujey  阅读(101)  评论(0)    收藏  举报