[ACCEPTED]-I/O concept flush vs sync-operating-system

Accepted answer
Score: 81

In Java, the flush() method is used in output streams 17 and writers to ensure that buffered data 16 is written out. However, according to the 15 Javadocs:

If the intended destination of 14 this stream is an abstraction provided by 13 the underlying operating system, for example 12 a file, then flushing the stream guarantees 11 only that bytes previously written to the 10 stream are passed to the operating system 9 for writing; it does not guarantee that 8 they are actually written to a physical 7 device such as a disk drive.

On the other 6 hand, FileDescriptor.sync() can be used to ensure that data buffered 5 by the OS is written to the physical device 4 (disk). This is the same as the sync call in 3 Linux / POSIX.

If your Java application really 2 needs to ensure that data is physically 1 written to disk, you may need to flush and sync, e.g.:

FileOutputStream out = new FileOutputStream(filename);

[...]

out.flush();
out.getFD().sync();

References:

More Related questions