我有一个类似 FilterOutputStream
的类。
public class WritableFilterChannel implements WritableChannel {
public WritableFilterChannel(final WritableByteChannel channel) {
super();
this.channel = channel;
}
// isOpen(), close() delegates to the channel
// write(ByteBuffer) overridden to work differently
protected WritableByteChannel channel;
}
当我传递 FileChannel
实例时,除了 close()
之外,没有办法 force()
它。
FileChannel#force
是否等同于 OutputStream#flush
?我总是需要调用它吗?
我必须这样做吗?
@Override
public void close() {
if (channel instanceof FileChannel) throws IOException {
((FileChannel) channel).force(); // general solution?
}
channel.close();
}
最佳答案
“同等”这个词太重了。 FileChannel.force(false)
与 OutputStream.flush()
类似。文件 channel 的force()方法在文件返回后比OutputStream 的flush() 方法提供了更强的保证。
显然,您不必 close() 调用了force() 方法的FileChannel。您应该仅在完成后关闭 channel 。但是,不能保证关闭 channel 会导致对其执行等效的强制操作。如果您需要 force() 的行为指定为 channel 闭包的一部分,那么您必须按照在 close() 方法中执行的方式显式调用它。
关于java - FileChannel#force 等同于 OutputStream#flush 吗?我总是需要调用它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859380/