如何检查OutputStream是否已关闭

无论如何都要检查OutputStream是否关闭而不尝试写入并捕获IOException

例如,考虑以下设计方法:

 public boolean isStreamClosed(OutputStream out){ if( /* stream isn't closed */){ return true; }else{ return false; } } 

什么可以替换/* stream isn't closed */与?

在你尝试写入它之前,底层流可能不知道它已关闭(例如,如果套接字的另一端关闭它)

最简单的方法是使用它并处理当时关闭时发生的事情,而不是先测试它。

无论您测试什么,总是有可能获得IOException,因此您无法避免exception处理代码。 添加此测试可能会使代码复杂化。

不幸的是,OutputStream API没有类似isClosed()方法。

所以,我只知道一个明确的方法:创建包含任何其他输出流的类StatusKnowingOutputStream并实现其close()方法,如下所示:

 public void close() { out.close(); closed = true; } 

现在添加方法isClosed()

 public boolean isClosed() { return closed; } 

OutputStream本身不支持这样的方法。 Closable接口的定义方式是,一旦调用close(),就会丢弃该OutputStream。

也许您应该重新考虑一下应用程序的设计,并检查为什么您没有这样做,并且您最终会在应用程序中运行仍然运行的闭合OutputStream实例。

 public boolean isStreamClosed(FileOutputStream out){ try { FileChannel fc = out.getChannel(); return fc.position() >= 0L; // This may throw a ClosedChannelException. } catch (java.nio.channels.ClosedChannelException cce) { return false; } catch (IOException e) { } return true; } 

这仅适用于FileOutputStream!

不。如果你实现自己的,你可以编写一个isClosed方法,但是如果你不知道具体的类,那么没有。 OutputStream只是一个抽象类。 这是它的实现:

  /** * Closes this output stream and releases any system resources * associated with this stream. The general contract of close * is that it closes the output stream. A closed stream cannot perform * output operations and cannot be reopened. * 

* The close method of OutputStream does nothing. * * @exception IOException if an I/O error occurs. */ public void close() throws IOException { }

通过使用out.checkError()

 while(!System.out.checkError()) { System.out.println('hi'); } 

在这里找到它: 如何在管道输入时让java退出