How do I flush a 'RandomAccessFile' (java)?

前端 未结 6 1674
孤街浪徒
孤街浪徒 2021-02-14 21:44

I\'m using RandomAccessFile in java:

file = new RandomAccessFile(filename, \"rw\");
...
file.writeBytes(...);

How can I ensure that this data i

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 22:02

    I reached here with the very same curiosity.

    And I really can't figure what need to flush on OS and not necessarily need to flush to Disk part means.

    In my opinion,

    The best thing matches to the concept of a managed flushing is getFD().sync(), as @AVD said,

    try(RandomAccessFile raw = new RandomAccessFile(file, "rw")) {
        raw.write...
        raw.write...
        raw.getFD().sync();
        raw.wirte...
    }
    

    which looks like, by its documentation, it works very much like what FileChannel#force(boolean) does with true.

    Now "rws" and "rwd" are look like they work as if specifying StandardOpenOption#SYNC and StandardOpenOption#DSYNC respectively while a FileChannel is open.

    try(RandomAccessFile raw = new RandomAccessFile(file, "rws")) {
        raw.write...
        raw.write...
        raw.wirte...
        // don't worry be happy, woo~ hoo~ hoo~
    }
    

提交回复
热议问题