实现Closeable或实现AutoCloseable [英] implements Closeable or implements AutoCloseable

查看:260
本文介绍了实现Closeable或实现AutoCloseable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,我找不到关于实现Closeable 实现AutoCloseable 接口。

I'm in the process of learning Java and I cannot find any good explanation on the implements Closeable and the implements AutoCloseable interfaces.

当我实现接口Closeable 时,我的Eclipse IDE创建了一个方法 public void close()抛出IOException

When I implemented an interface Closeable, my Eclipse IDE created a method public void close() throws IOException.

我可以使用 pw.close();来关闭流。 没有界面。但是,我无法理解如何使用该接口实现 close()方法。而且,这个界面的目的是什么?

I can close the stream using pw.close(); without the interface. But, I cannot understand how I can implement theclose() method using the interface. And, what is the purpose of this interface?

另外我想知道:如何检查 IOstream 真的关闭了?

Also I would like to know: how can I check if IOstream was really closed?

我使用的是以下基本代码

I was using the basic code below

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 {


}


推荐答案

在我看来,你对界面不是很熟悉。在您发布的代码中,您无需实施 AutoCloseable

It seems to me that you are not very familiar with interfaces. In the code you have posted you don't need to implement AutoCloseable.

您只需(或应该)实施 可关闭 AutoCloseable 如果您要实现自己的 PrintWriter ,它处理文件或需要关闭的任何其他资源。

You will only have to (or should) implement Closeable or AutoCloseable if you are about to implement an own PrintWriter which handles with files or any other resources which needs to be closed.

在您的实现中,只需调用 pw.close()即可。你应该在finally块中执行此操作:

In your implementation it is enough to call pw.close(). You should do this in a finally block:

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相关。在Java 7中,这可以做得更优雅(参见此答案)。

The code above is Java 6 related. In Java 7 this can be done more elegant (see this answer).

这篇关于实现Closeable或实现AutoCloseable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆