传统的try catch finally 方式是这样的
- public static void main(String[] args) {
- FileInputStream fileInputStream = null;
- try{
- // 捕获异常
- fileInputStream = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"));
- byte[] bytes = new byte[1024];
- int line = 0;
- while ((line = fileInputStream.read(bytes))!= -1){
- System.out.println(new String(bytes,0,line));
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //关闭流
- if(null != fileInputStream){
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
传统的写法导致层级太多,易读性差,不够简洁,JDK 1.8 之后推出了 try-with-resource 写法,大大提高了代码的可读性,使代码更加简洁,使用了try-with-resource是这样的
- public static void main(String[] args) {
- //把打开流的操作都放入try()块里
- try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"))) {
- byte[] bytes = new byte[1024];
- int line = 0;
- while ((line = fileInputStream.read(bytes))!= -1){
- System.out.println(new String(bytes,0,line));
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
try-with-resource 本质上跟我们自己关闭流是一样的,只不过是在编译的时候加上了 finally的代码块,让我们看看jdk的编译器帮我们做了什么事吧!
以下是反编译后的代码
- package com.network;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
-
- public class NetworkUtil {
-
- public static void main(String[] args) {
- try {
- FileInputStream e = new FileInputStream(new File("/Users/mac/Documents/合规业务组照片.zip"));
- Throwable var2 = null;
-
- try {
- byte[] bytes = new byte[1024];
- boolean line = false;
-
- int line1;
- while((line1 = e.read(bytes)) != -1) {
- System.out.println(new String(bytes, 0, line1));
- }
- } catch (Throwable var13) {
- var2 = var13;
- throw var13;
- } finally {
- if(e != null) {
- if(var2 != null) {
- try {
- e.close();
- } catch (Throwable var12) {
- var2.addSuppressed(var12);
- }
- } else {
- e.close();
- }
- }
-
- }
- } catch (IOException var15) {
- var15.printStackTrace();
- }
-
- }
- }