JDK8新特性之 try-with-resources

JDK8新特性之 try-with-resources

(供笔者学习记录)

什么是try-with-resources

  • 资源的关闭很多⼈停留在旧的流程上,jdk7新特性就有,但是很多⼈以为是jdk8的 在try( …)⾥声
    明的资源,会在try-catch代码块结束后⾃动关闭掉
  • 旧的方式:
public static void main(String[] args) throws IOException {
	 String path = "/Users/a.txt";
	 test(path);
 }
 
 private static void test(String filepath) throws FileNotFoundException {
	 OutputStream out = new FileOutputStream(filepath);
	 try {
	 	out.write((filepath+"abc程").getBytes());
	 } catch (Exception e) {
	 	e.printStackTrace();
	 }finally {
		 try {
		 	out.close();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	 }
 }
  • 新的方式
 private static void test(String filepath){
    try(OutputStream out = new FileOutputStream(filepath);) {
   	 	out.write((filepath+"abc程").getBytes());
    } catch (Exception e) {
    	e.printStackTrace();
    }
}
  • 注意点 :实现了AutoCloseable接⼝的类,在try()⾥声明该类实例的时候,try结束后⾃动调⽤的
    close⽅法,这个动作会早于finally⾥调⽤的⽅法
  • 不管是否出现异常,try()⾥的实例都会被调⽤close⽅法
  • try⾥⾯可以声明多个⾃动关闭的对象,越早声明的对象,会越晚被close掉

JDK9新特性之增强try-with-resource

  • 在JDK9中,改进了try-with-resources语句,在try外进⾏初始化,在括号内引⽤,即可实现
    资源⾃动关闭,多个变量则⽤分号进⾏分割
  • 不需要声明资源 out 就可以使⽤它,并得到相同的结果
 public static void main(String[] args) throws Exception {
	 String path = "/Users/a.txt";
	 	test(path);
	 }
	 private static void test(String filepath) throws FileNotFoundException {
		 OutputStream out = new FileOutputStream(filepath);
		 try (out) {
		 	out.write((filepath + "abc程").getBytes());
		 } catch (Exception e) {
		 	e.printStackTrace();
		 }
 }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值