为什么在JDK 7中,使用try-with-resources功能可以自动关闭文件?

Nic*_*.Xu 1 java

当我阅读这些Java IO教程时,try-with-resources不需要调用close()来关闭文件.为什么?

在第一个示例中,它在finally中调用close()方法

package com.mkyong.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("C:\\testing.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
} 
Run Code Online (Sandbox Code Playgroud)

但是在第二个例子中,它没有调用close()方法,它仍然有效.为什么?

package com.mkyong.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}
Run Code Online (Sandbox Code Playgroud)

Smu*_*tje 9

因为Java会为您处理结束.

try-with-resources语句是一个声明一个或多个资源的try语句.资源是在程序完成后必须关闭的对象.try-with-resources语句确保在语句结束时关闭每个资源.实现java.lang.AutoCloseable的任何对象(包括实现java.io.Closeable的所有对象)都可以用作资源.

(http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)