Writing Text Files in Java with FileWriter and BufferedWriter

Illustration for Writing Text Files in Java with FileWriter and BufferedWriter
By Last updated:

Every application that processes or stores information relies on input and output (I/O). From text editors saving content, to logging systems writing millions of records, to web servers persisting configuration files, I/O is at the heart of modern software. In Java, two widely used classes for writing text files are FileWriter and BufferedWriter.

While FileWriter offers a straightforward way to write characters to files, BufferedWriter improves efficiency by buffering data before writing it to disk. Together, they allow developers to build reliable, performant text-handling solutions.


Basics of Java I/O

Streams, Readers, and Writers

  • InputStream / OutputStream: Handle binary data.
  • Reader / Writer: Handle character (text) data.
  • FileWriter: A specialization of Writer to write character data into files.
  • BufferedWriter: Wraps another writer (like FileWriter) to reduce I/O operations by buffering output.

Example: Writing with FileWriter

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, Java FileWriter!\n");
            writer.write("Writing text files is simple.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example: Writing with BufferedWriter

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
            writer.write("Line 1: Writing with BufferedWriter");
            writer.newLine(); // adds a new line
            writer.write("Line 2: Efficient and fast.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Analogy: Using BufferedWriter is like pouring tea into a cup before sipping, instead of drinking directly from the kettle — more efficient and manageable.


Intermediate Concepts

Buffered I/O and Efficiency

  • FileWriter: Writes directly to the file system.
  • BufferedWriter: Buffers text in memory, flushing larger chunks at once.
  • Ideal for large files or frequent write operations.

RandomAccessFile

For non-sequential access (e.g., updating specific parts of a file), RandomAccessFile can complement writers.

Serialization

Objects can be serialized into text-based formats like JSON or XML for persistence.

Writing CSV, JSON, and XML Files

  • CSV: Use BufferedWriter with comma-separated values.
  • JSON/XML: Use libraries like Jackson, Gson, or DOM with writers.

Properties Files

The Properties class uses FileWriter and BufferedWriter to save configuration files.


Advanced I/O with NIO and NIO.2

Files API

Modern Java offers Files.write() methods to simplify text writing:

import java.nio.file.*;

public class FilesWriteExample {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("nio-example.txt");
        Files.writeString(path, "Hello from NIO.2!");
    }
}

Channels and Buffers

Use FileChannel with ByteBuffer for high-performance text and binary writing.

AsynchronousFileChannel

Supports non-blocking writes, useful in scalable applications.

File Locking

FileChannel.lock() prevents concurrent modifications in multi-threaded or distributed environments.


Performance & Best Practices

  • Always close writers using try-with-resources.
  • Use BufferedWriter for performance in large files.
  • Explicitly specify character encodings with OutputStreamWriter.
  • Avoid excessive flushes — batch writes instead.
  • Validate file paths to prevent overwriting critical files.

Framework Case Studies

  • Spring Boot: Writing log files and reports using writers.
  • Logging Frameworks (Log4j, SLF4J): Efficiently append logs with buffered writers.
  • Netty: Writes network data, often integrated with file systems.
  • Hibernate: Saves configurations or exports database schemas.
  • Microservices: Write configuration dumps or API responses to file storage.

Real-World Scenarios

  1. Log Writer: Append logs using BufferedWriter.
  2. CSV Exporter: Write database rows to CSV files.
  3. JSON Exporter: Export data in JSON format with FileWriter.
  4. REST API Export: Save API responses as text files.
  5. Report Generation: Automated scripts writing structured reports.

📌 What's New in Java Versions?

  • Java 7+: NIO.2 introduced simplified file APIs (Files.write()).
  • Java 8: Streams API integration for writing collections.
  • Java 11: Files.writeString() and Files.readString() convenience methods.
  • Java 17: Performance optimizations in I/O libraries.
  • Java 21: Virtual threads improve scalability for blocking I/O.

Conclusion & Key Takeaways

Writing text files is one of the most common tasks in Java. While FileWriter provides simplicity, BufferedWriter enhances performance and flexibility. Combined with modern NIO.2 utilities, they empower developers to build efficient and secure file-writing solutions.

Key Takeaways:

  • Use FileWriter for small/simple writes.
  • Use BufferedWriter for performance with large data.
  • Prefer try-with-resources for closing resources.
  • Always handle encoding explicitly.
  • Explore NIO.2 for advanced file operations.

FAQ

Q1. What’s the difference between FileWriter and BufferedWriter?
A: FileWriter writes characters directly; BufferedWriter buffers output for efficiency.

Q2. Can I append to a file with FileWriter?
A: Yes, by passing true as the second argument in the constructor.

Q3. How do I specify encoding with FileWriter?
A: Use OutputStreamWriter with FileOutputStream instead of FileWriter.

Q4. Is BufferedWriter faster than FileWriter?
A: Yes, for larger writes, because it reduces disk access.

Q5. How do I add new lines with BufferedWriter?
A: Use the newLine() method.

Q6. What happens if I don’t close the writer?
A: Data may not be flushed, causing incomplete writes.

Q7. Can I use BufferedWriter with FileWriter?
A: Yes, it’s the most common combination for efficient writing.

Q8. When should I use RandomAccessFile instead?
A: When you need non-sequential file writes or updates.

Q9. Does Java 11 simplify text writing?
A: Yes, with Files.writeString(path, text).

Q10. How do I prevent overwriting files accidentally?
A: Check file existence before writing or open in append mode.