代码一定得写的优雅一点!
你还在使用try-catch-finally关闭资源吗,如果是,那么就有点out了。皮皮甜手把手教你使用JDK7引用的try-with-resource。
JDK7之前资源的关闭姿势:
/**
* jdk7以前关闭流的方式
*
* @author hetiantian
* */
public class CloseResourceBefore7 {
private static final String FileName = "file.txt";
public static void main(String[] args) throws IOException {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(FileName);
char c1 = (char) inputStream.read();
System.out.println("c1=" + c1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
JDK7及以后关闭资源的正确姿势
try-with-resource Resource的定义:
所有实现了 java.lang.AutoCloseable[1] 接口(其中,它包括实现了 java.io.Closeable[2] 的所有对象),可以使用作为资源。简单Demo进行证实:实现java.la

本文介绍了JDK7引入的try-with-resource特性,用于更优雅地关闭资源,避免使用try-catch-finally。通过示例代码展示了如何使用此特性,并解释了其背后的编译原理和异常处理机制,特别是对异常屏蔽的处理。
最低0.47元/天 解锁文章
1648

被折叠的 条评论
为什么被折叠?



