在实际开发中,我们经常碰到资源的读写开关,例如我们在读取一个文件的时候,安装之前的代码习惯大部分是这样实现的:
(此处代码来自互联网)
public static void main(String[] args) throws Throwable {
try {
FileInputStream ins = new FileInputStream(new File("temp"));
Throwable throwException = null;
try {
System.out.println(ins.read());
} catch (Throwable throwable) {
throwException = throwable;
throw throwable;
} finally {
if (ins != null) {
if (throwException != null) {
try {
ins.close();
} catch (Throwable var11) {
throwException.addSuppressed(var11);
}
} else {
ins.close();
}
}
}
} catch (IOException exception) {
throw new RuntimeException(exception.getMessage(), exception);
}
}
其实自1.7之后,try-with-resource能比较优雅的处理资源的关闭问题。
改进后的代码如下:
public static void main(String[] args) throws Throwable {
try (FileInputStream ins = new FileInputStream(new File("temp"));) {
Throwable throwException = null;
try {
System.out.println(ins.read());
} catch (Throwable throwable) {
throwException = throwable;
throw throwable;
}
} catch (IOException exception) {
throw new RuntimeException(exception.getMessage(), exception);
}
}
这样就省去了一大段finally处理代码。