【发布时间】:2012-10-19 22:17:28
【问题描述】:
我正在学习 Java,在implements Closeable 和implements AutoCloseable 接口上找不到任何好的解释。
当我实现 interface Closeable 时,我的 Eclipse IDE 创建了一个方法 public void close() throws IOException。
我可以在没有接口的情况下使用pw.close(); 关闭流。但是,我无法理解如何使用接口实现close() 方法。而且,这个接口的用途是什么?
我也想知道:如何检查IOstream 是否真的关闭了?
我使用的是下面的基本代码
import java.io.*;
public class IOtest implements AutoCloseable {
public static void main(String[] args) throws IOException {
File file = new File("C:\\test.txt");
PrintWriter pw = new PrintWriter(file);
System.out.println("file has been created");
pw.println("file has been created");
}
@Override
public void close() throws IOException {
}
【问题讨论】:
-
我想所有的都已经说了,但也许你对下面关于尝试资源的文章感兴趣:docs.oracle.com/javase/tutorial/essential/exceptions/…。这也可能有助于理解给定的答案。