How to write a text file in Java

Writing text is the reverse of reading it: characters are encoded into bytes with a charset, then handed to the operating system. Java offers about ten ways to do this, and they differ in whether they replace or append, whether they buffer, whether they report errors, and when the data is really on disk. This page runs each one and measures them on the same output.

Contents

How writing a text file works

Writing text happens in three steps, and each approach on this page takes care of some of them for you:

  1. Encode: characters become bytes using a charset. All the Files methods use UTF-8 unless you pass another one.
  2. Buffer: small writes are collected in memory and handed to the operating system in large blocks, because each hand-over is a system call and costs far more than copying a few bytes.
  3. Persist: the operating system keeps the data in its own cache and writes it to the disk later. Your program has "written" the file long before the bytes are physically stored.
The ways to write text, and what each is for
ApproachSinceBuffers?Best for
Files.writeStringJava 11One callA whole small text at once
Files.write(path, lines)Java 7YesA list of lines
Files.newBufferedWriterJava 7YesMany writes, large output
FileWriter (in a BufferedWriter)Java 1.1With the wrapperCode based on File; simple appending
OutputStreamWriterJava 1.1Small internal bufferText onto any OutputStream
PrintWriterJava 1.1With a buffered writer insideFormatted output with printf
RandomAccessFileJava 1.0NoChanging bytes in place at a known position
FileChannelJava 1.4NoPositional writes and forcing data to disk

Every example is a complete program, compiled and run on JDK 21, that writes into a temporary file and reads it back so you can see exactly what ended up on disk.

Writing a whole file: writeString and write

When the content is already in memory, one call writes it. The program also writes the same text in two charsets, because the charset decides how many bytes each character takes and whether a character can be written at all.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class WriteWholeFile {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("write-demo");
        Path notes = dir.resolve("notes.txt");

        // 1. Files.writeString (Java 11+): creates the file, or replaces all of it
        Files.writeString(notes, "first version\n");
        Files.writeString(notes, "second version\n");
        System.out.println("writeString twice: " + Files.readAllLines(notes));

        // 2. The same call with APPEND adds to the end instead
        Files.writeString(notes, "appended line\n", StandardOpenOption.APPEND);
        System.out.println("after APPEND:      " + Files.readAllLines(notes));

        // 3. Files.write with a list: a line separator after every line, the last one too
        Path list = dir.resolve("list.txt");
        Files.write(list, List.of("alpha", "beta", "gamma"));
        System.out.println("write(lines): " + Files.size(list) + " bytes for 14 letters");

        // 4. The charset decides the bytes: the same text in UTF-8 and ISO-8859-1
        Path utf8 = dir.resolve("utf8.txt");
        Path latin1 = dir.resolve("latin1.txt");
        Files.writeString(utf8, "café €5");
        Files.writeString(latin1, "café", StandardCharsets.ISO_8859_1);
        System.out.println("\"café €5\" in UTF-8:   " + Files.size(utf8) + " bytes");
        System.out.println("\"café\" in ISO-8859-1: " + Files.size(latin1) + " bytes");
        try {
            Files.writeString(latin1, "€5", StandardCharsets.ISO_8859_1);
        } catch (IOException e) {
            System.out.println("\"€5\" in ISO-8859-1:   " + e.getClass().getSimpleName());
        }

        for (Path p : List.of(notes, list, utf8, latin1, dir)) {
            Files.delete(p);
        }
    }
}

Output:

Output
writeString twice: [second version]
after APPEND:      [second version, appended line]
write(lines): 17 bytes for 14 letters
"café €5" in UTF-8:   10 bytes
"café" in ISO-8859-1: 4 bytes
"€5" in ISO-8859-1:   UnmappableCharacterException
  • Without options, Files.writeString uses CREATE, TRUNCATE_EXISTING and WRITE: it creates the file, or throws away the old content. After two calls only "second version" is left.
  • StandardOpenOption.APPEND adds to the end instead. With APPEND alone the file must already exist; add CREATE to create it when missing. See file open options for all of them.
  • Files.write(path, lines) writes the system line separator after every line, including the last. 14 letters plus three \n make 17 bytes on Linux and macOS; on Windows the separator is \r\n, giving 20.
  • "café €5" is 7 characters but 10 bytes in UTF-8: é takes 2 bytes and € takes 3. In ISO-8859-1 every character is one byte, but € does not exist in that charset, so writing it throws UnmappableCharacterException rather than writing a wrong byte.

Writing incrementally: BufferedWriter, FileWriter and OutputStreamWriter

When output is produced bit by bit, such as rows of a report or log entries, open a writer once and write to it repeatedly. The program writes a 1,001-line CSV file, appends to a log in three separate runs, and writes text onto a raw OutputStream.

Java
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
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 WriteIncrementally {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("incremental");

        // 5. Files.newBufferedWriter: the standard way to write a lot of text
        Path csv = dir.resolve("squares.csv");
        try (BufferedWriter w = Files.newBufferedWriter(csv)) {
            w.write("n,square");
            w.newLine();
            for (int n = 1; n <= 1000; n++) {
                w.write(n + "," + n * n);
                w.newLine();
            }
        }                                               // close() flushes the rest
        List<String> rows = Files.readAllLines(csv);
        System.out.println("newBufferedWriter: " + rows.size() + " lines, last \""
                + rows.get(rows.size() - 1) + "\"");

        // 6. java.io FileWriter: the boolean argument chooses append
        Path log = dir.resolve("app.log");
        for (int run = 1; run <= 3; run++) {
            try (Writer w = new BufferedWriter(
                    new FileWriter(log.toFile(), StandardCharsets.UTF_8, true))) {
                w.write("run " + run + "\n");
            }
        }
        System.out.println("FileWriter(append=true), 3 runs: " + Files.readAllLines(log));

        // 7. OutputStreamWriter: text onto any OutputStream (socket, ZIP entry, response)
        Path out = dir.resolve("stream.txt");
        try (OutputStream os = new FileOutputStream(out.toFile());
             Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
            w.write("Grüße\n");
        }
        System.out.println("OutputStreamWriter: \"Grüße\" + newline = "
                + Files.size(out) + " bytes");

        for (Path p : List.of(csv, log, out, dir)) {
            Files.delete(p);
        }
    }
}

Output:

Output
newBufferedWriter: 1001 lines, last "1000,1000000"
FileWriter(append=true), 3 runs: [run 1, run 2, run 3]
OutputStreamWriter: "Grüße" + newline = 8 bytes
  • Files.newBufferedWriter collects writes in an 8,192-character buffer. The 2,002 calls to write and newLine become a few large writes to the operating system. The last part of the buffer is written by close(), so try-with-resources is not optional: without it, the end of the file is lost.
  • new FileWriter(file, charset, true) opens the file in append mode, so each of the three runs added a line. The constructor that takes a charset was added in Java 11. The older new FileWriter(file) uses the platform default charset, which has been UTF-8 only since Java 18 (JEP 400).
  • OutputStreamWriter encodes characters onto any byte stream. "Grüße" plus a newline is 8 bytes: ü and ß take 2 bytes each. This is how you write text into a socket, a ZIP entry or an HTTP response.

Formatted output: PrintWriter and its traps

PrintWriter adds print, println and printf, which makes reports and aligned columns easy. It also has two behaviors that cause real bugs, and this program shows both.

Java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;

public class PrintWriterTraps {

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

        // 8. PrintWriter adds print, println and printf
        try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(report))) {
            pw.printf(Locale.ROOT, "%-8s|%10.2f%n", "total", 1234.5);
            pw.printf(Locale.GERMANY, "%-8s|%10.2f%n", "total", 1234.5);
        }
        System.out.print(Files.readString(report));

        // Trap: PrintWriter never throws IOException; it only sets an error flag
        OutputStream broken = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                throw new IOException("disk full");
            }
        };
        PrintWriter pw = new PrintWriter(broken);
        pw.println("important data");
        pw.flush();
        System.out.println("no exception was thrown; checkError() = " + pw.checkError());
        pw.close();
        Files.delete(report);
    }
}

Output:

Output
total   |   1234.50
total   |   1234,50
no exception was thrown; checkError() = true
  • The pattern %-8s|%10.2f left-aligns the label in 8 columns and right-aligns the number in 10 with 2 decimals.
  • The same printf wrote 1234.50 with Locale.ROOT and 1234,50 with Locale.GERMANY. Without a locale argument, printf uses the machine's default, so a file meant for another program can change format depending on where it runs. Pass Locale.ROOT for machine-readable output.
  • PrintWriter never throws IOException. When the underlying stream failed with "disk full", the program got no exception at all; the only sign is checkError() returning true. If the data matters, call checkError() after writing, or use a BufferedWriter, which does throw.

Changing a file in place: RandomAccessFile

All the writers above produce a file from the start or append to its end. RandomAccessFile can seek to any byte position and overwrite bytes there, leaving the rest of the file untouched. The test file holds order lines whose status field is padded to 4 characters, so "NEW " can be replaced by "DONE" without shifting anything.

Java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HexFormat;

public class WriteAtPosition {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("orders", ".txt");
        Files.writeString(file, "order 1 status=NEW \norder 2 status=NEW \n");

        // 9. RandomAccessFile: overwrite bytes in place, without rewriting the file
        try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "rw")) {
            long pos = Files.readString(file).indexOf("NEW ", 20);  // order 2's status
            raf.seek(pos);
            raf.write("DONE".getBytes(StandardCharsets.UTF_8));     // same length: 4 bytes
            raf.seek(raf.length());                                 // the end: append
            raf.write("order 3 status=NEW \n".getBytes(StandardCharsets.UTF_8));
        }
        System.out.print(Files.readString(file));

        // writeUTF and writeChars look like text methods, but they do not write plain text
        try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "rw")) {
            raf.setLength(0);                                      // truncate
            raf.writeUTF("Hi");
            raf.writeChars("Hi");
        }
        byte[] bytes = Files.readAllBytes(file);
        System.out.println("writeUTF(\"Hi\") + writeChars(\"Hi\") = "
                + HexFormat.ofDelimiter(" ").formatHex(bytes));
        Files.delete(file);
    }
}

Output:

Output
order 1 status=NEW 
order 2 status=DONE
order 3 status=NEW 
writeUTF("Hi") + writeChars("Hi") = 00 02 48 69 00 48 00 69
  • Only the 4 bytes of order 2's status were written; the other bytes of the file were not touched. This works only when the new text has exactly the same number of bytes as the old. Inserting or deleting text in the middle of a file is not possible with any API: you have to rewrite everything after that point. That is why the status was padded.
  • Seeking to length() and writing appends; setLength(0) truncates the file.
  • writeUTF and writeChars sound like text methods but are binary formats for DataInputStream. The bytes show it: writeUTF("Hi") wrote a 2-byte length (00 02) before 48 69, and writeChars("Hi") wrote 2 bytes per character (00 48 00 69, UTF-16). A text editor shows both as garbage. To write text with RandomAccessFile, encode it yourself with getBytes(StandardCharsets.UTF_8) and call write, as the first part of the program does.

For fixed-size records and reading at a position, see the RandomAccessFile page.

Writing with FileChannel and forcing data to disk

FileChannel writes ByteBuffers, either at the current position or at an offset you pass. It also has force, which waits until the operating system has passed the data to the storage device. The test file is a small journal of two entries that must not be lost if the machine loses power.

Java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class WriteWithChannel {

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

        // 10. FileChannel: write bytes, at the end or at a position, and force them to disk
        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.WRITE,
                StandardOpenOption.APPEND)) {
            for (String entry : new String[] {"debit 40\n", "credit 25\n"}) {
                ch.write(StandardCharsets.UTF_8.encode(entry));
                ch.force(false);            // data reaches the storage device before we go on
            }
            System.out.println("size after 2 appends: " + ch.size() + " bytes");
        }

        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.WRITE)) {
            ch.write(ByteBuffer.wrap("DEBIT".getBytes(StandardCharsets.UTF_8)), 0);
        }
        System.out.print(Files.readString(file));
        Files.delete(file);
    }
}

Output:

Output
size after 2 appends: 19 bytes
DEBIT 40
credit 25
  • "debit 40\n" is 9 bytes and "credit 25\n" is 10, so the file has 19 bytes after the two appends.
  • force(false) waits until the file's content is on the device; force(true) also includes metadata such as the modification time. Each call is slow, often milliseconds, so use it where losing data is unacceptable, such as journals and payment records, not for ordinary output. Opening the file with StandardOpenOption.SYNC or DSYNC gives the same guarantee for every write.
  • ch.write(buffer, 0) overwrote the first 5 bytes with "DEBIT" without moving the channel's position. See NIO channels for more.

Flushing, failures and safe replacement

The next program shows what happens around the write itself:

  • when buffered data really reaches the file;
  • how to refuse to overwrite an existing file;
  • what happens when the folder does not exist;
  • how to replace a file without readers ever seeing it half-written.
Java
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;

public class FlushAndFailures {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("flush-demo");
        Path file = dir.resolve("log.txt");

        // Data sits in the 8 KB buffer until flush() or close()
        BufferedWriter w = Files.newBufferedWriter(file);
        w.write("first entry");
        System.out.println("before flush, bytes on disk: " + Files.size(file));
        w.flush();
        System.out.println("after flush, bytes on disk:  " + Files.size(file));
        w.close();

        // CREATE_NEW refuses to overwrite an existing file
        try {
            Files.writeString(file, "x", StandardOpenOption.CREATE_NEW);
        } catch (FileAlreadyExistsException e) {
            System.out.println("CREATE_NEW on existing file: FileAlreadyExistsException");
        }

        // Writing never creates missing parent directories
        Path nested = dir.resolve("reports/2026/q1.txt");
        try {
            Files.writeString(nested, "data");
        } catch (NoSuchFileException e) {
            System.out.println("missing parent directory: NoSuchFileException");
        }
        Files.createDirectories(nested.getParent());
        Files.writeString(nested, "data");
        System.out.println("after createDirectories: written " + Files.size(nested) + " bytes");

        // Safe replace: write to a temporary file, then move it over the target
        Path tmp = Files.createTempFile(dir, "log", ".tmp");
        Files.writeString(tmp, "complete new content\n");
        Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
        System.out.println("after atomic replace: " + Files.readString(file).strip());

        Files.delete(nested);
        Files.delete(nested.getParent());
        Files.delete(nested.getParent().getParent());
        Files.delete(file);
        Files.delete(dir);
    }
}

Output:

Output
before flush, bytes on disk: 0
after flush, bytes on disk:  11
CREATE_NEW on existing file: FileAlreadyExistsException
missing parent directory: NoSuchFileException
after createDirectories: written 4 bytes
after atomic replace: complete new content
  • After write("first entry") the file is still 0 bytes: the 11 characters are in the writer's buffer. Only flush() or close() passes them on.
  • CREATE_NEW fails with FileAlreadyExistsException if the file exists, which is a safe way to avoid overwriting.
  • Writing to reports/2026/q1.txt fails with NoSuchFileException because the folders do not exist. Files.createDirectories creates the whole chain, and does nothing if it already exists.
  • For files other programs read, such as configuration, write the new content to a temporary file in the same directory, then move it over the original with ATOMIC_MOVE. Readers see either the old file or the new one, never a partial write. ATOMIC_MOVE throws AtomicMoveNotSupportedException when the file system cannot do it, for example across different drives.

How fast is each approach?

The program writes the same 200,000 log lines (about 9 MB) five ways. Each way runs 3 times and the fastest run is reported. This is a rough comparison, not a benchmark; see the JMH page for measuring properly.

Java
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class WriteSpeed {

    interface Job {
        void write(Path file, List<String> lines) throws IOException;
    }

    public static void main(String[] args) throws IOException {
        List<String> lines = new ArrayList<>();
        for (int i = 0; i < 200_000; i++) {
            lines.add("2026-11-14T10:15:30 INFO order " + i + " shipped");
        }
        Path file = Files.createTempFile("speed", ".txt");

        time("Files.write(lines)", file, lines, Files::write);
        time("BufferedWriter", file, lines, (f, ls) -> {
            try (BufferedWriter w = Files.newBufferedWriter(f)) {
                for (String l : ls) {
                    w.write(l);
                    w.newLine();
                }
            }
        });
        time("FileWriter, no BufferedWriter", file, lines, (f, ls) -> {
            try (Writer w = new FileWriter(f.toFile(), StandardCharsets.UTF_8)) {
                for (String l : ls) {
                    w.write(l);
                    w.write('\n');
                }
            }
        });
        time("PrintWriter, autoFlush=true", file, lines, (f, ls) -> {
            try (PrintWriter w = new PrintWriter(new FileWriter(f.toFile(),
                    StandardCharsets.UTF_8), true)) {
                for (String l : ls) {
                    w.println(l);                   // flushes after every line
                }
            }
        });
        time("FileOutputStream, per line", file, lines, (f, ls) -> {
            try (OutputStream out = new FileOutputStream(f.toFile())) {
                for (String l : ls) {
                    out.write((l + "\n").getBytes(StandardCharsets.UTF_8));
                }
            }
        });
        System.out.printf("file size: %.1f MB%n", Files.size(file) / 1e6);
        Files.delete(file);
    }

    // Runs each job 3 times and reports the fastest
    static void time(String name, Path file, List<String> lines, Job job) throws IOException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            job.write(file, lines);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-30s %,6d ms%n", name, best / 1_000_000);
    }
}

Output (2-CPU Linux machine, JDK 21; absolute times will differ on yours):

Output
Files.write(lines)                 32 ms
BufferedWriter                     19 ms
FileWriter, no BufferedWriter      54 ms
PrintWriter, autoFlush=true        97 ms
FileOutputStream, per line         86 ms
file size: 9.1 MB
  • Files.write and BufferedWriter are the fastest. Files.write writes through a BufferedWriter internally, so the difference between them is mostly measurement noise.
  • FileWriter without a BufferedWriter is slower. It has a small byte buffer in its encoder, so it is not as slow as fully unbuffered output, but every write call goes through the encoder separately.
  • PrintWriter with autoFlush set to true flushes on every println, so each line becomes its own system call. It is among the slowest, and the cause is easy to miss because the flushing is hidden in a constructor argument.
  • Writing each line straight to a FileOutputStream also makes one system call per line, and pays for creating a byte array per line too.

Which one to use

Choosing a way to write text
NeedUse
Write a small stringFiles.writeString(path, text)
Write a list of linesFiles.write(path, lines)
Add to the end of a fileEither of the above with StandardOpenOption.CREATE, StandardOpenOption.APPEND
Many writes or large outputFiles.newBufferedWriter in try-with-resources
Formatted outputPrintWriter around a buffered writer, with Locale.ROOT and a checkError() check
Text onto an OutputStreamOutputStreamWriter with an explicit charset
Change bytes at a known positionRandomAccessFile or FileChannel.write(buffer, position), with the same byte length
Data that must survive a power failureFileChannel.force, or the SYNC / DSYNC open options
Replace a file other programs readWrite a temporary file, then Files.move with ATOMIC_MOVE

To read files back, see reading a text file in Java.