在 JDK 7 中引入了哪些與 Java 中異常處理相關的新特性?


自 Java 7 起引入了 try-with-resources。這樣,我們就可以在 try 塊中宣告一個或多個資源,並在使用後自動關閉它們(在 try 塊的末尾)。

我們在 try 塊中宣告的資源應擴充套件 java.lang.AutoCloseable 類。

示例

以下程式演示了 Java 中的 try-with-resources。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopying {
   public static void main(String[] args) {
      try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt"));
      FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){
         byte[] buffer = new byte[1024];
         int length;
         while ((length = inS.read(buffer)) > 0) {
            outS.write(buffer, 0, length);
         }
         System.out.println("File copied successfully!!");
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

輸出

File copied successfully!!

更新時間:07-Aug-2019

66 次瀏覽

開啟你的 職業生涯

完成課程以取得認證

開始
廣告
© . All rights reserved.