00:00

FileWriter Class in Java: Writing Text Files

Last updated:

Saving notes, exporting a report or writing a log means putting text in a file. FileWriter is the classic java.io class for that: it encodes characters and writes them to a file, either replacing its content or appending to it.

This tutorial covers its constructors and methods, and two practical examples.

1. What Is FileWriter in Java?

FileWriter is a convenience subclass of OutputStreamWriter that opens a file for writing text. It was added in Java 1.1.

  • A missing file is created; an existing file is replaced unless you choose append mode.
  • Since Java 11 you can pass a Charset; otherwise the default charset is used (UTF-8 since Java 18).
  • For many small writes, wrap it in a BufferedWriter.

2. FileWriter Class Hierarchy

FileWriter class hierarchyFileWriter extends OutputStreamWriter, which extends the abstract class Writer and Object. It implements Appendable, Closeable, Flushable and AutoCloseable. Modern alternatives are Files.newBufferedWriter, Files.writeString and Files.write with a list of lines.ObjectextendsWriterabstract classextendsOutputStreamWriterencodes charactersextendsFileWriterwrites text to a fileAppendableCloseableFlushableAutoCloseableimplementsModern alternativesFiles.newBufferedWriter()Files.writeString()Files.write(path, lines)

Swipe sideways to see the whole diagram.

3. Constructors of FileWriter

ConstructorDescription
FileWriter(String fileName) / FileWriter(File file)Replaces the file content; default charset.
FileWriter(String fileName, boolean append)Appends when append is true.
FileWriter(File file, Charset charset)Explicit charset (Java 11).
FileWriter(File file, Charset charset, boolean append)Explicit charset and append mode (Java 11).

All of them throw an IOException if the file cannot be created or opened, for example when the folder does not exist.

4. Commonly Used Methods

MethodDescription
void write(String str)Writes a string.
void write(int c)Writes one character.
Writer append(CharSequence csq)Writes text and returns the writer (Java 5).
void flush()Pushes buffered data to the file.
void close()Flushes and closes the file.

5. Example: Creating and Appending to a To-Do List

A to-do app creates a task list, then later adds a task without losing the existing ones.

TodoList.java
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TodoList {
    public static void main(String[] args) throws IOException {
        Path todo = Files.createTempFile("todo", ".txt");

        // First run: create the list (replaces any existing content)
        try (FileWriter out = new FileWriter(todo.toFile(), StandardCharsets.UTF_8)) {
            out.write("[ ] Book train tickets\n");
            out.write("[ ] Pay electricity bill\n");
        }

        // Later: add one more task (append mode)
        try (FileWriter out = new FileWriter(todo.toFile(), StandardCharsets.UTF_8, true)) {
            out.write("[ ] Call the plumber\n");
        }

        System.out.print(Files.readString(todo));
        System.out.println("Tasks: " + Files.readAllLines(todo).size());
        Files.delete(todo);
    }
}
Output
[ ] Book train tickets
[ ] Pay electricity bill
[ ] Call the plumber
Tasks: 3

How the code works

  1. new FileWriter(file, StandardCharsets.UTF_8) starts a fresh list, replacing any old content.
  2. new FileWriter(file, StandardCharsets.UTF_8, true) (Java 11) opens the same file in append mode.
  3. Try-with-resources closes each writer, so the text is flushed to the file.

6. Example: Writing Meeting Notes

A team bot writes stand-up notes as a small Markdown file.

MeetingNotes.java
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class MeetingNotes {
    public static void main(String[] args) throws IOException {
        Path notes = Files.createTempFile("standup", ".md");
        List<String> done = List.of("Fixed login timeout", "Reviewed payment PR");
        List<String> next = List.of("Deploy release 3.2");

        try (Writer out = new FileWriter(notes.toFile(), StandardCharsets.UTF_8)) {
            out.write("# Stand-up, 16 Nov\n\n## Done\n");
            for (String item : done) out.write("- " + item + "\n");
            out.write("\n## Next\n");
            for (String item : next) out.write("- " + item + "\n");
        }

        System.out.print(Files.readString(notes));
        Files.delete(notes);
    }
}
Output
# Stand-up, 16 Nov

## Done
- Fixed login timeout
- Reviewed payment PR

## Next
- Deploy release 3.2

How the code works

  1. The headings and bullet lists are written with write(String).
  2. Loops write one list item per line.
  3. Files.readString() reads the result back for display.

7. Common Mistakes and Best Practices

  • Overwriting a file by accident. Use the append constructor to add text.
  • Not closing the writer. Buffered text may never reach the file.
  • Assuming missing folders are created. Create them first with Files.createDirectories().
  • Omitting the charset on Java 17 or earlier. Output varied by operating system.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1 and 1.4FileWriter; the File + append constructor in 1.4.
Java 11Constructors with a Charset; Files.writeString().
Java 18UTF-8 becomes the default charset (JEP 400).
Java 25No API changes.

9. Summary

  • FileWriter writes text to a file, creating it if needed.
  • By default it replaces the content; pass true to append.
  • Pass a Charset (Java 11+), and close the writer.
  • For one-shot writes, Files.writeString() is simpler.

Related Tutorials

10. Official Java Documentation References