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 a whole file: writeString and write Writing incrementally: BufferedWriter, FileWriter and OutputStreamWriter Formatted output: PrintWriter and its traps Changing a file in place: RandomAccessFile Writing with FileChannel and forcing data to disk Flushing, failures and safe replacement How fast is each approach? Which one to use
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:
- Encode: characters become bytes using a charset. All the
methods use UTF-8 unless you pass another one.Files - 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.
- 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.
| Approach | Since | Buffers? | Best for |
|---|---|---|---|
Files.writeString | Java 11 | One call | A whole small text at once |
Files.write(path, lines) | Java 7 | Yes | A list of lines |
Files.newBufferedWriter | Java 7 | Yes | Many writes, large output |
FileWriterBufferedWriter | Java 1.1 | With the wrapper | Code based on File |
OutputStreamWriter | Java 1.1 | Small internal buffer | Text onto any OutputStream |
PrintWriter | Java 1.1 | With a buffered writer inside | Formatted output with printf |
RandomAccessFile | Java 1.0 | No | Changing bytes in place at a known position |
FileChannel | Java 1.4 | No | Positional 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.
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:
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,
usesFiles.writeString ,CREATE andTRUNCATE_EXISTING : it creates the file, or throws away the old content. After two calls only "second version" is left.WRITE adds to the end instead. WithStandardOpenOption.APPEND alone the file must already exist; addAPPEND to create it when missing. SeeCREATEfile open options for all of them. writes the system line separator after every line, including the last. 14 letters plus threeFiles.write(path, lines) make 17 bytes on Linux and macOS; on Windows the separator is\n , giving 20.\r\n- "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€ rather than writing a wrong byte.UnmappableCharacterException
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
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:
newBufferedWriter: 1001 lines, last "1000,1000000"
FileWriter(append=true), 3 runs: [run 1, run 2, run 3]
OutputStreamWriter: "Grüße" + newline = 8 bytes
collects writes in an 8,192-character buffer. The 2,002 calls toFiles.newBufferedWriter andwrite become a few large writes to the operating system. The last part of the buffer is written bynewLine , so try-with-resources is not optional: without it, the end of the file is lost.close() 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 oldernew FileWriter(file, charset, true) uses the platform default charset, which has been UTF-8 only since Java 18 (JEP 400).new FileWriter(file) encodes characters onto any byte stream. "Grüße" plus a newline is 8 bytes:OutputStreamWriter 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
PrintWriterprintprintlnprintf
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:
total | 1234.50
total | 1234,50
no exception was thrown; checkError() = true
- The pattern
left-aligns the label in 8 columns and right-aligns the number in 10 with 2 decimals.%-8s|%10.2f - The same
wroteprintf with1234.50 andLocale.ROOT with1234,50 . Without a locale argument,Locale.GERMANY uses the machine's default, so a file meant for another program can change format depending on where it runs. Passprintf for machine-readable output.Locale.ROOT never throwsPrintWriter . When the underlying stream failed with "disk full", the program got no exception at all; the only sign isIOException returningcheckError() . If the data matters, calltrue after writing, or use acheckError() , which does throw.BufferedWriter
Changing a file in place: RandomAccessFile
All the writers above produce a file from the start or append to its end. RandomAccessFileseek
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:
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
and writing appends;length() truncates the file.setLength(0) andwriteUTF sound like text methods but are binary formats forwriteChars . The bytes show it:DataInputStream wrote a 2-byte length (writeUTF("Hi") ) before00 02 , and48 69 wrote 2 bytes per character (writeChars("Hi") , UTF-16). A text editor shows both as garbage. To write text with00 48 00 69 , encode it yourself withRandomAccessFile and callgetBytes(StandardCharsets.UTF_8) , as the first part of the program does.write
For fixed-size records and reading at a position, see the
Writing with FileChannel and forcing data to disk
FileChannelByteBufferforce
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:
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.
waits until the file's content is on the device;force(false) 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 withforce(true) orStandardOpenOption.SYNC gives the same guarantee for every write.DSYNC overwrote the first 5 bytes with "DEBIT" without moving the channel's position. Seech.write(buffer, 0)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.
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:
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
the file is still 0 bytes: the 11 characters are in the writer's buffer. Onlywrite("first entry") orflush() passes them on.close() fails withCREATE_NEW if the file exists, which is a safe way to avoid overwriting.FileAlreadyExistsException- Writing to
fails withreports/2026/q1.txt because the folders do not exist.NoSuchFileException creates the whole chain, and does nothing if it already exists.Files.createDirectories - 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
. Readers see either the old file or the new one, never a partial write.ATOMIC_MOVE throwsATOMIC_MOVE when the file system cannot do it, for example across different drives.AtomicMoveNotSupportedException
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
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):
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
andFiles.write are the fastest.BufferedWriter writes through aFiles.write internally, so the difference between them is mostly measurement noise.BufferedWriter without aFileWriter is slower. It has a small byte buffer in its encoder, so it is not as slow as fully unbuffered output, but everyBufferedWriter call goes through the encoder separately.write withPrintWriter set toautoFlush flushes on everytrue , 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.println- Writing each line straight to a
also makes one system call per line, and pays for creating a byte array per line too.FileOutputStream
Which one to use
| Need | Use |
|---|---|
| Write a small string | Files.writeString(path, text) |
| Write a list of lines | Files.write(path, lines) |
| Add to the end of a file | Either of the above with StandardOpenOption.CREATE, StandardOpenOption.APPEND |
| Many writes or large output | Files.newBufferedWriter |
| Formatted output | PrintWriterLocale.ROOTcheckError() |
Text onto an OutputStream | OutputStreamWriter |
| Change bytes at a known position | RandomAccessFileFileChannel.write(buffer, position) |
| Data that must survive a power failure | FileChannel.forceSYNCDSYNC |
| Replace a file other programs read | Write a temporary file, then Files.moveATOMIC_MOVE |
To read files back, see