Class AtomicFileWriter

java.lang.Object
net.blockhost.commons.core.io.AtomicFileWriter

public final class AtomicFileWriter extends Object

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:

  1. Write content to a temporary file in the same directory as the target
  2. Atomically move the temporary file to the target path
  3. 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 Details

    • write

      public static void write(Path path, byte[] content) throws IOException
      Writes the given byte array to the target path atomically.
      Parameters:
      path - the target file path
      content - the bytes to write
      Throws:
      IOException - if an I/O error occurs
      NullPointerException - if path or content is null
    • write

      public static void write(Path path, String content) throws IOException
      Writes the given string to the target path atomically using UTF-8 encoding.
      Parameters:
      path - the target file path
      content - the string to write
      Throws:
      IOException - if an I/O error occurs
      NullPointerException - if path or content is null
    • write

      public static void write(Path path, IOConsumer<OutputStream> writer) throws IOException

      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 path
      writer - a consumer that writes content to the provided output stream
      Throws:
      IOException - if an I/O error occurs
      NullPointerException - if path or writer is null