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

标签 java

当我阅读这篇文章时 Java IO tutorials , try-with-resources 将不需要调用 close() 来关闭文件。为什么?

在第一个例子中,它最终调用了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();
            }
        }

    }
} 

但是在第二个例子中,它没有调用 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();
        } 

    }
}

最佳答案

因为 Java 会为您处理关闭。

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

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

关于java - 为什么在 JDK 7 中,使用 try-with-resources 特性可以自动关闭文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27856593/

相关文章:

java - 已为此响应调用 "getOutputStream()"

java - Firebase Multi-Tenancy 与 Play 框架取决于 HTTP 请求的 header 值

java - url 模式语法 (java servlet)

java - 如何编写多线程代码来加速繁重的重复性任务?

@Service 和@Autowired 注释的 Java/Spring 问题

java - 如何调用重载方法的最具体版本?

java - (PDFBox)java.awt.print.PrinterException : Printer is not accepting job

java - Alfresco ServiceRegistry 无法注入(inject) Junit 中

java - 正在加载Java Applet ...网络: Cache entry not found

java - 如何正确访问gwtp服务实例中的文件?