-->

Is FileChannel#force is equivalent to OutputStream

2019-09-19 02:08发布

问题:

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.