public static void rename ( final Path oldName , final Path newName ) throws IOException { checkNotNull ( oldName ) ; checkNotNull ( newName ) ; final boolean sameDir = Files . isSameFile ( oldName . getParent ( ) , newName . getParent ( ) ) ; // rename the file Files . move ( oldName , newName , StandardCopyOption . ATOMIC_MOVE ) ; // fsync the parent dir fsync ( newName . getParent ( ) ) ; if ( ! sameDir ) { fsync ( oldName . getParent ( ) ) ; } }
Perform an atomic rename of oldName - &gt ; newName and fsync the containing directory . This is only truly fsync - safe if both files are in the same directory but it will at least try to do the right thing if the files are in different directories .