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

前端 未结 6 1668
孤街浪徒
孤街浪徒 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 21:52

    here's what i do in my app:

    rf.close();
    rf = new RandomAccessFile("mydata", "rw");
    

    this is give 3-4times gain in performance compared to getFd().sync() and 5-7 times compared to "rws' mode

    deoes exactly what the original question proposed: passes on unsaved data to the OS and out of JVM. Doesn't physically write to disk, and therefore introduces no annoying delays

    0 讨论(0)
  • 2021-02-14 21:53

    You can use getFD().sync() method.

    0 讨论(0)
  • 2021-02-14 21:57

    The only classes that provide a .flush() method are those that actually maintain their own buffers. As java.io.RandomAccessFile does not itself maintain a buffer, it does not need to be flushed.

    0 讨论(0)
  • 2021-02-14 22:00

    I learned that you can't..

    Some related links here: http://www.cs.usfca.edu/~parrt/course/601/lectures/io.html and here: http://tutorials.jenkov.com/java-io/bufferedwriter.html

    0 讨论(0)
  • 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~
    }
    
    0 讨论(0)
  • 2021-02-14 22:10

    Have a look carefully at RandomAccessFile constructor javadoc:

    The "rws" and "rwd" modes work much like the force(boolean) method of the FileChannel class, passing arguments of true and false, respectively, except that they always apply to every I/O operation and are therefore often more efficient. If the file resides on a local storage device then when an invocation of a method of this class returns it is guaranteed that all changes made to the file by that invocation will have been written to that device. This is useful for ensuring that critical information is not lost in the event of a system crash. If the file does not reside on a local device then no such guarantee is made.

    0 讨论(0)
提交回复
热议问题