溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用try-with-resource對io流進行關(guān)閉

發(fā)布時間:2021-01-05 15:03:49 來源:億速云 閱讀:192 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹如何使用try-with-resource對io流進行關(guān)閉,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

傳統(tǒng)寫法操作io流

例如如下讀取的文件的io流,我們之前可能會這樣寫

public class Main {
 public static void main(String[] args) {
  FileInputStream fileInputStream =null;
  try {
   fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt")); //打開流
   byte[] bytes = new byte[1024];
   int line = 0; 
   //讀取數(shù)據(jù)
   while ((line = fileInputStream.read(bytes))!= -1){
    System.out.println(new String(bytes,0,line));
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  }finally {
   if (fileInputStream != null){ //不為空
    try {
     fileInputStream.close(); //關(guān)閉流
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

使用try-with-resource寫法優(yōu)雅操作io流

public class Main {
 public static void main(String[] args) {
  //把打開流的操作都放入try()塊里
  try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt"))) {
   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()中可以編寫多個文件io流或網(wǎng)絡io流。讓我們看看java編譯器是怎么幫我們實現(xiàn)的

借助idea查看編譯后的代碼

如何使用try-with-resource對io流進行關(guān)閉

可以看到編譯后的代碼,java編譯器自動替我們加上了關(guān)閉流的操作。所以跟我們自己關(guān)閉流是一樣的。try-with-resource這樣優(yōu)雅的寫法還是不錯的,讓代碼看起來不那么臃腫。

注意jdk1.7以后才可以用

關(guān)于如何使用try-with-resource對io流進行關(guān)閉就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI