try-with-resources
try-with-resources 可以自动关闭资源。非常方便。
try 语句里面可以声明一个或者多个资源。
资源指的是对象,必须在程序执行完后关闭,比如IO流 执行完后要关闭流。
这个对象必须实现了java.lang.AutoCloseable接口。
以前关闭流的方式:
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("千字文.txt");
out = new FileOutputStream("千字文02.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
使用try-with-resources关闭流
public static void main(String []args)throws Exception{
//在try语句里面声明资源 会自动关闭资源
try(FileInputStream is=new FileInputStream("千字文.txt");
FileOutputStream os=new FileOutputStream("out.txt");
){
int i;
while ((i=is.read())!=-1){
os.write((byte)i);
}
}
}
如上代码,语句执行完之后会自动关闭流。
资源的close方法调用顺序和资源创建顺序相反。
实现java.lang.AutoCloseable接口 自定义资源
代码如下:
public class TryWithResourcesDemo {
public static void main(String[] args) throws Exception {
try (ResourceOne resourceOne = new ResourceOne();
ResourceTwo resourceTwo = new ResourceTwo();
) {
resourceOne.doSomething();
resourceTwo.doSomething();
}
}
}
class ResourceOne implements AutoCloseable {
void doSomething() {
System.out.println("ResourceOne 做事情。。。。。。");
}
@Override
public void close() throws Exception {
System.out.println("resourceOne 关闭资源...........");
}
}
class ResourceTwo implements AutoCloseable {
void doSomething() {
System.out.println("ResourceTwo 做事情。。。。。。");
}
@Override
public void close() throws Exception {
System.out.println("resourceTwo 关闭资源------------");
}
}
输出结果:
从上图输出可以看出,关闭资源的顺序和创建资源的顺序相反。
try-with-resources 的实现
反编译上面的代码,如下:
public class TryWithResourcesDemo {
public TryWithResourcesDemo() {
}
public static void main(String[] args) throws Exception {
ResourceOne resourceOne = new ResourceOne();
Throwable var2 = null;
try {
ResourceTwo resourceTwo = new ResourceTwo();
Throwable var4 = null;
try {
resourceOne.doSomething();
resourceTwo.doSomething();
} catch (Throwable var27) {
var4 = var27;
throw var27;
} finally {
if (resourceTwo != null) {
if (var4 != null) {
try {
resourceTwo.close();
} catch (Throwable var26) {
var4.addSuppressed(var26);
}
} else {
resourceTwo.close();
}
}
}
} catch (Throwable var29) {
var2 = var29;
throw var29;
} finally {
if (resourceOne != null) {
if (var2 != null) {
try {
resourceOne.close();
} catch (Throwable var25) {
var2.addSuppressed(var25);
}
} else {
resourceOne.close();
}
}
}
}
}
可以看出, try-with-resources 就是一个语法糖,它在代码编译后增加了finally块 来进行关闭资源。