Java 中的 ARM 是什麼?
資源是一種實現 AutoClosable 介面的物件。只要在程式中使用了資源,建議在使用後將其關閉。
最初,此任務使用 finally 塊完成。
示例
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class FinalExample { public static void main(String[] args) throws IOException { File file = null; FileInputStream inputStream = null; try { file = new File("D:\source\sample.txt"); inputStream = new FileInputStream(file); Scanner sc = new Scanner(inputStream); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch(IOException ioe) { ioe.printStackTrace(); } finally { inputStream.close(); } } }
輸出
This is a sample file with sample text
ARM
Java 中的 ARM 即自動資源管理,它在 Java7 中引入,其中應在 try 塊中宣告資源,它們將在該塊的末尾自動關閉。它也稱為 try-with-resources 塊,我們在此中宣告的物件應為資源,即它們應屬於 AutoClosable 型別。
以下是 try-with-resources 語句的語法 −
try(ClassName obj = new ClassName()){ //code…… }
從 JSE7 開始引入 try-with-resources 語句。在此中,我們在 try 塊中宣告一個或多個資源,這些資源將在使用後 (在 try 塊末尾) 自動關閉。
我們在 try 塊中宣告的資源應擴充套件 java.lang.AutoCloseable 類。
示例
Following program demonstrates the try-with-resources in Java. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class FinalExample { public static void main(String[] args) throws IOException { try(FileInputStream inputStream = new FileInputStream(new File("D:\source\sample.txt"));) { Scanner sc = new Scanner(inputStream); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch(IOException ioe) { ioe.printStackTrace(); } } }
輸出
This is a sample file with sample text
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!!
廣告