当我阅读这篇文章时 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/