有没有办法在不尝试写入并捕获IOException
的情况下检查OutputStream
是否关闭?
例如,考虑以下人为的方法:
public boolean isStreamClosed(OutputStream out){
if( /* stream isn't closed */){
return true;
}else{
return false;
}
}
你可以用什么代替
/* 流没有关闭 */
?有没有办法在不尝试写入并捕获IOException
的情况下检查OutputStream
是否关闭?
例如,考虑以下人为的方法:
public boolean isStreamClosed(OutputStream out){
if( /* stream isn't closed */){
return true;
}else{
return false;
}
}
/* 流没有关闭 */
?在尝试向底层流写入数据之前(例如,如果套接字的另一端关闭),可能无法知道底层流是否已关闭。
最简单的方法是使用它并处理它关闭后会发生什么,而不是先进行测试。
无论你测试什么,总有可能会出现IOException,因此你不能避免异常处理代码。添加这个测试可能会使代码变得复杂。
isClosed()
这样的方法进行了解释:_"底层流可能直到尝试将其写入才知道它是否已关闭"_,因此被接受,谢谢 :) - chrisbunney很遗憾OutputStream API没有类似于isClosed()
的方法。
因此,我只知道一种明确的方法:创建一个名为StatusKnowingOutputStream
的类,它包装任何其他输出流并实现其close()
方法如下:
public void close() {
out.close();
closed = true;
}
现在添加一个名为isClosed()
的方法。
public boolean isClosed() {
return closed;
}
finally
子句中处理它,以便在发生异常时将其关闭,那么处理它的状态可能会更加困难。 - Aritzpublic 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才能实现这一点!
OutputStream本身不支持这样的方法。 Closable接口的定义方式是,一旦调用close(),就会处理该OutputStream。
也许你应该重新审视一下应用程序的设计,并检查为什么你没有这样做,而导致一个关闭的OutputStream实例仍然在你的应用程序中运行。
/**
* Closes this output stream and releases any system resources
* associated with this stream. The general contract of <code>close</code>
* is that it closes the output stream. A closed stream cannot perform
* output operations and cannot be reopened.
* <p>
* The <code>close</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void close() throws IOException {
}
OutputStream
不是一个抽象类吗?因此它可以提供一些实现,不是吗? - chrisbunneyverify
。import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import java.io.InputStream;
class MyTest {
@Test
public void testInputStreamCloseCalled() throws IOException {
final InputStream spied = spy(...)
// Do something that should call .close() on the spied InputStream
spied.close()
verify(spied, times(1)).close();
}
}
...
是你正在操作的输入流。
也可以与输出流一起使用。
while(!System.out.checkError()) {
System.out.println('hi');
}
在这里找到了它:如何在管道到head时让Java退出