How to really persist your file in Java

Use FileChannel.force(boolean) or FileDescriptor.sync() to force data to be persistent on disk. Either of them can work. FileChannel.force use FileDispacther.force[1] and it calls fdatasync or fsync in Java 8. 

When you use OutputStream.flush, it does not guarantee the data to be written to disk, just flush it to OS. Better to use FileOutputStream.getChannel().force(true) or FileOutputStream.getFD().sync() to guarantee the persistency, performance might not be good.

Special Thanks to Yongkun. He wrote very good blog post. [2]

[1] http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/solaris/native/sun/nio/ch/FileDispatcherImpl.c#l141

[2] http://yongkunphd.blogspot.com/2013/12/how-fsync-works-in-java.html

9 Ağustos 2016

Posted In: fdatasync, FileChannel, fsync, java, OutputStream