java arm_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块中声明,并且资源将在该块末尾自动关闭。这也称为尝试资源块,我们在其中声明的对象应该是资源,即它们应该是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

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) {

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!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值