序言
由于之前说的finalizer 不推荐被使用,所以在java类库中的许多方法都是通过调用close来实现手动关闭资源的。
java7之前
那么在java7之前关闭资源最常见的方式就是 try-finally,show me code
static void readMyLine(String path) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
try {
bufferedReader.readLine();
} finally {
bufferedReader.close();
}
}
看起来没毛病,但是呢我们继续加。
static void readMyLine(String source, String target) throws IOException {
InputStream in = new FileInputStream(source);
try {
OutputStream out = new FileOutputStream(target);
try {
...
}finally {
out.close();
}
} finally {
in.close();
}
}
java7 try-with-resources
那么在java7呢就加入了一个接口 AutoCloseable 接口,它代表的是必须被关闭的资源。
那么上面的两个例子就可以简写成这样
static void readMyLine(String path) throws IOException {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path));) {
bufferedReader.readLine();
}
}
第二个
static void readMyLine(String source, String target) throws IOException {
try (
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)
) {
....
}
}
总结
在处理关闭资源的时候,能用 try-with-resources 就使用,代码清晰简洁的同时,能让你在处理异常的时候变的更有价值。而try-finally 是做不到的。