Java 中的 ARM 是什么?

javaobject oriented programmingprogramming更新于 2024/2/11 5:32:17

资源是实现 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;
     尝试 {
          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();
      }
   }
}

输出

这是一个带有示例文本的示例文件

ARM

Java 中的 ARM 代表自动资源管理,它是在 Java7 中引入的,其中资源应在 try 块中声明,并且它们将在该块结束时自动关闭。它也被称为 try-with 资源块,我们在其中声明的对象应该是资源,即它们应该是 AutoClosable 类型。

以下是 try-with-resources 语句 −

的语法
try(ClassName obj = new ClassName()){
   //code……
}

从 JSE7 开始引入 try-with-resources 语句。在其中,我们在 try 块中声明一个或多个资源,这些资源将在使用后自动关闭。 (在 try 块的末尾)

我们在 try 块中声明的资源应该扩展 java.lang.AutoCloseable 类。

示例

以下程序演示了 Java 中的 try-with-resources。
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 资源中声明多个资源,它们将在块结束时立即关闭。

示例

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) {
     尝试(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("文件复制成功!!");
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

输出

文件复制成功!!

相关文章


有用资源