try-with-resource 不调用close()方法也能回收垃圾

发布时间:2022-03-01 12:09:10 作者:yexindonglai@163.com 阅读(854)

 

传统的try catch finally 方式是这样的

  1. public static void main(String[] args) {
  2. FileInputStream fileInputStream = null;
  3. try{
  4. // 捕获异常
  5. fileInputStream = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"));
  6. byte[] bytes = new byte[1024];
  7. int line = 0;
  8. while ((line = fileInputStream.read(bytes))!= -1){
  9. System.out.println(new String(bytes,0,line));
  10. }
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. } finally {
  14. //关闭流
  15. if(null != fileInputStream){
  16. try {
  17. fileInputStream.close();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. }
  23. }

传统的写法导致层级太多,易读性差,不够简洁,JDK 1.8 之后推出了 try-with-resource 写法,大大提高了代码的可读性,使代码更加简洁,使用了try-with-resource是这样的

  1. public static void main(String[] args) {
  2. //把打开流的操作都放入try()块里
  3. try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"))) {
  4. byte[] bytes = new byte[1024];
  5. int line = 0;
  6. while ((line = fileInputStream.read(bytes))!= -1){
  7. System.out.println(new String(bytes,0,line));
  8. }
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }
  12. }

try-with-resource 本质上跟我们自己关闭流是一样的,只不过是在编译的时候加上了 finally的代码块,让我们看看jdk的编译器帮我们做了什么事吧!

以下是反编译后的代码

  1. package com.network;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. public class NetworkUtil {
  6. public static void main(String[] args) {
  7. try {
  8. FileInputStream e = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"));
  9. Throwable var2 = null;
  10. try {
  11. byte[] bytes = new byte[1024];
  12. boolean line = false;
  13. int line1;
  14. while((line1 = e.read(bytes)) != -1) {
  15. System.out.println(new String(bytes, 0, line1));
  16. }
  17. } catch (Throwable var13) {
  18. var2 = var13;
  19. throw var13;
  20. } finally {
  21. if(e != null) {
  22. if(var2 != null) {
  23. try {
  24. e.close();
  25. } catch (Throwable var12) {
  26. var2.addSuppressed(var12);
  27. }
  28. } else {
  29. e.close();
  30. }
  31. }
  32. }
  33. } catch (IOException var15) {
  34. var15.printStackTrace();
  35. }
  36. }
  37. }

 

关键字Java