开发者

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

I'm using RandomAccessFile in java:

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

How can I ensure that this data is flushed to the Operating System? There is no file.flush() method. (Note that I don't actually expect 开发者_StackOverflow社区it to be physically written, I'm content with it being flushed to the operating system, so that the data will survive a tomcat crash but not necessarily an unexpected server power loss).

I'm using tomcat6 on Linux.


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.


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.


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


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


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~
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜