目录
3、try - with - resources 写法资源自动关闭原理
1、常规 try - catch - finally 写法
public String resdFile1(String filePath){
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
return bufferedReader.readLine();
} catch (IOException e) {
// 异常日志
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、try - with - resources 写法
public String resdFile2(String filePath) {
try (BufferedReader bufferedReader =
new BufferedReader(new FileReader(filePath))) {
return bufferedReader.readLine();
} catch (Exception e) {
// 异常日志
return null;
}
}
3、try - with - resources 写法资源自动关闭原理
以 BufferedReader 为例
public class BufferedReader extends Reader {
private Reader in;
private char cb[];
// 其他代码省略
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
}
public abstract class Reader implements Readable, Closeable {
abstract public void close() throws IOException;
}
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
public interface AutoCloseable {
void close() throws Exception;
}
- BufferedReader 继承 Reader 抽象类并实现其抽象方法 close()
- close() 最终来自 AutoCloseable
- JAVA 1.7 以上版本,AutoCloseable 对象的 close() 方法,会在退出 try -with-resources 块时自动调用
4、动手实现拥有自动关闭功能的类
自定义一个类,实现 AutoCloseable 的 close() 方法
public class AutoCloseableTest implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("关闭资源!!!");
}
}
正常执行时的运行情况
使用 main 方法进行调用操作,查看控制台日志信息:代码执行完成后自动执行了 close() 方法,打印了 「关闭资源!!!」 信息
public static void main(String[] args) {
try (AutoCloseableTest autoCloseableTest = new AutoCloseableTest()) {
System.out.println("autoCloseableTest.getClass() = "
+ autoCloseableTest.getClass());
} catch (Exception e) {
System.out.println("出现异常");
}
}
// 控制台执行日志:
// autoCloseableTest.getClass() = class tryWithResources.AutoCloseableTest
// 关闭资源!!!
代码块中存在异常情况时
先是执行了 close() 方法又执行了 catch 块内的代码,抛出的异常类型为 空指针异常,与执行过程中实际的异常一致。
public static void main(String[] args) {
try (AutoCloseableTest autoCloseableTest = new AutoCloseableTest()) {
System.out.println("autoCloseableTest.getClass() = "
+ autoCloseableTest.getClass());
Object obj = null;
// 空指针异常
obj.toString();
} catch (Exception e) {
System.out.println("e.getClass() = " + e.getClass());
System.out.println("出现异常");
}
}
// 控制台日志信息:
// autoCloseableTest.getClass() = class tryWithResources.AutoCloseableTest
// 关闭资源!!!
// e.getClass() = class java.lang.NullPointerException
// 出现异常