// Created on savesnippets.com ยท https://savesnippets.com/D6uvY8nBTqbbH2 import java.io.IOException; import java.nio.file.*; import static java.nio.file.StandardCopyOption.*; class Demo { static void atomicWrite(Path target, byte[] data) throws IOException { Path tmp = Files.createTempFile(target.getParent(), "." + target.getFileName() + ".", ".tmp"); try { Files.write(tmp, data); Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING); } catch (IOException e) { Files.deleteIfExists(tmp); throw e; } } public static void main(String[] args) throws IOException { atomicWrite(Path.of("/var/lib/myapp/state.json"), "{\"ready\":true}\n".getBytes()); } }