资源是实现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
Java中的ARM代表自动资源管理,它是在Java7中引入的,其中资源应在try块中声明,并且资源将在该块末尾自动关闭。这也称为尝试资源块,我们在其中声明的对象应该是资源,即它们应该是AutoClosable类型。
以下是try-with-resources语句的语法-
try(ClassName obj = new ClassName()){ //代码…… }
从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
您还可以在try-with资源中声明多个资源,它们将在块末尾立即关闭。
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!!