Class AtomicFileWriter
java.lang.Object
net.blockhost.commons.core.io.AtomicFileWriter
Utility class for writing files atomically using a write-to-temp-then-rename strategy.
This prevents partial or corrupt files if the process crashes mid-write. The sequence is:
- Write content to a temporary file in the same directory as the target
- Atomically move the temporary file to the target path
- If atomic move is not supported by the filesystem, fall back to a regular move
The temporary file is always cleaned up, even if an error occurs during writing.
Usage
// Write a string
AtomicFileWriter.write(path, "key: value\n");
// Write bytes
AtomicFileWriter.write(path, serializedBytes);
// Write via an OutputStream (e.g. for YAML serializers)
AtomicFileWriter.write(path, out -> yaml.dump(data, new OutputStreamWriter(out)));
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidWrites the given byte array to the target path atomically.static voidWrites the given string to the target path atomically using UTF-8 encoding.static voidwrite(Path path, IOConsumer<OutputStream> writer) Writes to the target path atomically using a consumer that receives anOutputStream.
-
Method Details
-
write
Writes the given byte array to the target path atomically.- Parameters:
path- the target file pathcontent- the bytes to write- Throws:
IOException- if an I/O error occursNullPointerException- if path or content is null
-
write
Writes the given string to the target path atomically using UTF-8 encoding.- Parameters:
path- the target file pathcontent- the string to write- Throws:
IOException- if an I/O error occursNullPointerException- if path or content is null
-
write
Writes to the target path atomically using a consumer that receives an
OutputStream.This overload is useful when the caller wants to serialize directly to a stream (e.g. YAML or JSON writers) without first buffering the entire content into a byte array.
- Parameters:
path- the target file pathwriter- a consumer that writes content to the provided output stream- Throws:
IOException- if an I/O error occursNullPointerException- if path or writer is null
-