我正在学习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 {
}发布于 2012-10-30 22:45:03
在我看来,您对接口不是很熟悉。在您发布的代码中,您不需要实现AutoCloseable。
如果您要实现自己的处理文件或任何其他需要关闭的资源的PrintWriter,则只需要(或应该)实现Closeable或AutoCloseable。
在您的实现中,调用pw.close()就足够了。您应该在finally块中执行此操作:
PrintWriter pw = null;
try {
File file = new File("C:\\test.txt");
pw = new PrintWriter(file);
} catch (IOException e) {
System.out.println("bad things happen");
} finally {
if (pw != null) {
try {
pw.close();
} catch (IOException e) {
}
}
}上面的代码与Java 6相关。在Java7中,这可以做得更好(参见this answer)。
发布于 2012-10-30 22:46:18
Closeable extends AutoCloseable,专门用于IO流:它抛出IOException而不是Exception,并且是幂等的,而AutoCloseable不提供这种保证。
这在两个接口的javadoc中都有解释。
实现AutoCloseable (或Closeable)允许将类用作Java7中引入的try-with-resources构造的资源,该构造允许在块的末尾自动关闭此类资源,而不必添加显式关闭资源的finally块。
您的类并不表示可关闭的资源,而且实现此接口绝对没有意义:IOTest不能被关闭。它甚至不可能实例化它,因为它没有任何实例方法。请记住,实现接口意味着在类和接口之间存在 is -a关系。你在这里没有这样的关系。
发布于 2017-03-17 20:12:01
下面是一个小示例
public class TryWithResource {
public static void main(String[] args) {
try (TestMe r = new TestMe()) {
r.generalTest();
} catch(Exception e) {
System.out.println("From Exception Block");
} finally {
System.out.println("From Final Block");
}
}
}
public class TestMe implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println(" From Close - AutoCloseable ");
}
public void generalTest() {
System.out.println(" GeneralTest ");
}
}下面是输出:
GeneralTest
From Close - AutoCloseable
From Final Blockhttps://stackoverflow.com/questions/13141302
复制相似问题