aspose file tools*
The moose likes I/O and Streams and the fly likes fflush and fsync Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "fflush and fsync " Watch "fflush and fsync " New topic
Author

fflush and fsync

Raees Uzhunnan
Ranch Hand

Joined: Aug 15, 2002
Posts: 126
Should we use fflush and fsync on java at all. if so how .. in other terms how do we make sure a java write is definitely written into the disk and not into the I/O buffer ?

in C and C++ we get the two APIs fflush and fsync for the same purpose

Thanks


Sun Certified Enterprise Architect
Java Technology Blog
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I think you're asking if Java has an equivalent to C's fflush and fsync. There are no methods called either fflush or fsync in Java. But if you're using a Writer or a Stream (e.g. a FileWriter or FileOutputStream) then you should call flush() to ensure that everything in the buffers has been written to disk. Calling close() also accomplishes this (so you really only need flush() if you want to keep the stream open afterwards for some reason). For writers and outputstreams, there is no need for fsync or any equivalent; it's all handled by flush() or close(). If you're using a RandomAccessFile you need to call close() at the end to achieve the effect of a fflush and fsync, and if you're using a FileChannel you can call either close() or force() - the latter allows the channel to remain open, like flush(). For other classes, just look at the API and see what options they offer. Some sort of close() operation is most common in Java.


"I'm not back." - Bill Harding, Twister
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In fact, in both RandomAccessFile and FileOutputStream, you can call getFD() to get the FileDescriptor. This has a method sync(), which you can call, to ensure that the OS flushes all buffers. That is not the same as flushing a Java stream.

I don't know how worthwhile or necessary it is to call this method, but it does exist.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Ah yes, I forgot about that. It would be nice to know if there are circumstances where close() is not enough, where you really need to do a getFD().sync() before closing. That seems an absurdly poor design if so, hiding a vital function in a separate class. It might account for some bad behavior I've seen on a few filesystems though. How annoying.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: fflush and fsync