带资源的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 catch-finally都是捕获异常,然后流关闭等等,代码总是这样的:
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