Is FileChannel#force is equivalent to OutputStream#flush? Do I always have to call it?

人盡茶涼 提交于 2020-01-06 19:26:17

问题


I have a class works like 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;
}

When I pass an instance of FileChannel, there is no way to force() other than close() it.

Is FileChannel#force is equivalent to OutputStream#flush? Do I always have to call it?

Do I have to do like this?

@Override
public void close() {
    if (channel instanceof FileChannel) throws IOException {
        ((FileChannel) channel).force(); // general solution?
    }
    channel.close();
}

回答1:


"Equivalent" is too strong a word. FileChannel.force(false) is similar to OutputStream.flush(). FileChannel's force() method offers stronger guarantees about the state of the file after it returns than OutputStream's flush() method.

Obviously you do not have to close() the FileChannel that you called the force() method on. You should only close the channel when you have finished with it. However, there is no guarantee that closing the channel will cause the equivalent of a force operation on it. If you need the behavior that force() specifies as part of the channel closure then you must explicitly call it the way you are doing in your close() method.



来源:https://stackoverflow.com/questions/34859380/is-filechannelforce-is-equivalent-to-outputstreamflush-do-i-always-have-to-ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!