private static void writeAtomically(final File file, final File tmpDir, OutputStreamConsumer f) throws IOException { final File tmpFile = new File(tmpDir, StringUtils.format(".%s.%s", file.getName(), UUID.randomUUID())); try { try (final FileOutputStream out = new FileOutputStream(tmpFile)) { // Pass f an uncloseable stream so we can fsync before closing. f.accept(uncloseable(out)); // fsync to avoid write-then-rename-then-crash causing empty files on some filesystems. out.getChannel().force(true); } // No exception thrown; do the move. java.nio.file.Files.move( tmpFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING ); } finally { tmpFile.delete(); } }