Class ThreadSafeWriter

java.lang.Object
com.log4rich.util.ThreadSafeWriter

public class ThreadSafeWriter extends Object
Thread-safe file writer with buffering support. Provides synchronized access to file writing operations with automatic initialization, parent directory creation, and resource management.
  • Constructor Details

    • ThreadSafeWriter

      public ThreadSafeWriter(File file)
      Creates a new ThreadSafeWriter with default settings. Uses UTF-8 encoding, immediate flush enabled, and 8KB buffer size.
      Parameters:
      file - the file to write to
    • ThreadSafeWriter

      public ThreadSafeWriter(File file, Charset charset, boolean immediateFlush, int bufferSize)
      Creates a new ThreadSafeWriter with the specified settings.
      Parameters:
      file - the file to write to
      charset - the character encoding to use
      immediateFlush - whether to flush after each write
      bufferSize - the buffer size in bytes
  • Method Details

    • initialize

      public void initialize() throws IOException
      Initializes the writer. Creates parent directories if needed. This method is called automatically when the first write occurs.
      Throws:
      IOException - if initialization fails
    • write

      public void write(String text) throws IOException
      Writes a string to the file. The writer is automatically initialized if not already done.
      Parameters:
      text - the text to write
      Throws:
      IOException - if writing fails
    • flush

      public void flush() throws IOException
      Flushes any buffered data to the file. This method is safe to call even if the writer is closed.
      Throws:
      IOException - if flushing fails
    • close

      public void close() throws IOException
      Closes the writer and releases resources. This method is safe to call multiple times.
      Throws:
      IOException - if closing fails
    • isClosed

      public boolean isClosed()
      Checks if the writer is closed.
      Returns:
      true if the writer is closed, false otherwise
    • getFile

      public File getFile()
      Gets the file this writer is writing to.
      Returns:
      the file being written to
    • getFileSize

      public long getFileSize()
      Gets the current file size.
      Returns:
      the file size in bytes, or 0 if the file doesn't exist