java中带参数的try(){}语法含义详解

带参数的try(){}语法含义

带资源的try语句(try-with-resource)

最简形式为

1

2

3

4

try(Resource res = xxx)//可指定多个资源

{

     work with res

}

try块退出时,会自动调用res.close()方法,关闭资源。

PS:在coreJava第9版的第一卷的486页有解释。

挺好用的语法,不用写一大堆finally来关闭资源,所有实现Closeable的类声明都可以写在里面,最常见于流操作,socket操作,新版的httpclient也可以;

需要注意的是

try()的括号中可以写多行声明,每个声明的变量类型都必须是Closeable的子类,用分号隔开。楼上说不能关两个流的落伍了

补充一下:在没有这个语法之前,流操作一般是这样写的:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

InputStream is = null;

OutputStream os = null;

try {

    //...

} catch (IOException e) {

    //...

}finally{

    try {

        if(os!=null){

            os.close();

        }

        if(is!=null){

            is.close();

        }

    } catch (IOException e2) {

        //...

    }

}    

而现在你可以这样写:

1

2

3

4

5

6

7

8

try(

    InputStream is = new FileInputStream("...");

    OutputStream os = new FileOutputStream("...");

){

    //...

}catch (IOException e) {

    //...

}

生活一下就美好了

对try(){}的简单理解

以前使用try catch-finally都是捕获异常,然后流关闭等等,代码总是这样的:

好比往FileOutputStream写东西

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@Test

  public void test2() throws IOException {

    File file = new File("E://test");

    if (!file.exists()) {

      file.createNewFile();

    }

    FileOutputStream fileOutputStream = new FileOutputStream(file);

    try {

      System.out.println("do something...");

      fileOutputStream.write("aaa".getBytes());

      fileOutputStream.flush();

    } catch (Exception e) {

      System.out.println("do ...");

    } finally {

      fileOutputStream.close();

    }

  }

这样写很难受,可以进行优化

将FileOutputStream fileOutputStream = new FileOutputStream(file)放到try()里面,也可以放多个

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Test

public void test2() throws IOException {

  File file = new File("E://test");

  if (!file.exists()) {

    file.createNewFile();

  }

  

  try( FileOutputStream fileOutputStream = new FileOutputStream(file);) {

    System.out.println("do something...");

    fileOutputStream.write("aaa".getBytes());

    fileOutputStream.flush();

  } catch (Exception e) {

    System.out.println("do ...");

  }

}

try()里每个声明的变量类型都必须是Closeable的子类,就一个close方法

相当于系统自动将关闭操作放到了finally里面而不需要我们自己写了,很nice

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值