第一种写法:
try(InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt")){ /*........................................*/ } catch (Exception e) { e.printStackTrace(); }
第二种写法:
try { InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt") } catch (Exception e) { e.printStackTrace(); }finally { }
第一种 情况的()中的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便
第二种 如果{}中的代码块出现了异常,会被catch捕获,然后执行catch中的代码,接着执行finally中的码,其中catch中的代码有了异常才会被执行,finally中的代码无论有没有异常都会被执行
从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
The try
-with-resources statement is a try
statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try
-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
带有resources的try语句声明一个或多个resources。resources是在程序结束后必须关闭的对象。try-with-resources语句确保在语句末尾关闭每个resources。任何实现java.lang.AutoCloseable,包括实现了java.io.Closeable的类,都可以
作为resources使用。