Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

flush

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 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.

like image 427
Tim Cooper Avatar asked Sep 26 '11 02:09

Tim Cooper


2 Answers

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.

like image 146
Jonathan Callen Avatar answered Sep 18 '22 06:09

Jonathan Callen


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.

like image 39
Stas Avatar answered Sep 18 '22 06:09

Stas