好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/llkoio/article/details/78939148

查看更多关于java中带参数的try(){}语法含义详解的详细内容...

  阅读:15次