序言

由于之前说的finalizer 不推荐被使用,所以在java类库中的许多方法都是通过调用close来实现手动关闭资源的。

java7之前

那么在java7之前关闭资源最常见的方式就是 try-finally,show me code

  1. static void readMyLine(String path) throws IOException {
  2. BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
  3. try {
  4. bufferedReader.readLine();
  5. } finally {
  6. bufferedReader.close();
  7. }
  8. }

看起来没毛病,但是呢我们继续加。

  1. static void readMyLine(String source, String target) throws IOException {
  2. InputStream in = new FileInputStream(source);
  3. try {
  4. OutputStream out = new FileOutputStream(target);
  5. try {
  6. ...
  7. }finally {
  8. out.close();
  9. }
  10. } finally {
  11. in.close();
  12. }
  13. }

看起来眼花撩乱,确实使用起来是略麻烦了。

java7 try-with-resources

那么在java7呢就加入了一个接口 AutoCloseable 接口,它代表的是必须被关闭的资源。
那么上面的两个例子就可以简写成这样

  1. static void readMyLine(String path) throws IOException {
  2. try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path));) {
  3. bufferedReader.readLine();
  4. }
  5. }

第二个

  1. static void readMyLine(String source, String target) throws IOException {
  2. try (
  3. InputStream in = new FileInputStream(source);
  4. OutputStream out = new FileOutputStream(target)
  5. ) {
  6. ....
  7. }
  8. }

无比清爽,而且不用去嵌套回收。

总结

在处理关闭资源的时候,能用 try-with-resources 就使用,代码清晰简洁的同时,能让你在处理异常的时候变的更有价值。而try-finally 是做不到的。