Java Write Files
Choosing a Way to Write a File
| Method | Writes | Keeps a file open for multiple writes? | Best for |
|---|---|---|---|
Files.writeString(path, text, options...) | One String | No | Small text output: a JSON document, a report |
Files.write(path, lines, options...) | An Iterable of lines, each followed by a line separator | No | A list of lines you already have in memory |
Files.write(path, bytes, options...) | A byte[] | No | Small binary data |
Files.newBufferedWriter(path, options...) | Text, piece by piece | Yes | Large or incremental output: exports, generated files |
PrintWriter around a writer | Formatted text (printf, println) | Yes | Reports and aligned tables |
Files.newOutputStream(path, options...) | Bytes, piece by piece | Yes | Large binary output (FileOutputStream and OutputStream lessons) |
All the Files methods encode text as UTF-8 unless you pass a charset, and all of them accept open options that control what happens to an existing file.
Overwriting, Appending and Writing Lines
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import static java.nio.file.StandardOpenOption.*;
public class W1 {
public static void main(String[] args) throws IOException {
Path file = Path.of("todo.txt");
Files.writeString(file, "buy ink\n");
Files.writeString(file, "renew domain\n");
System.out.print("after two writeString calls:\n" + Files.readString(file));
Files.writeString(file, "pay hosting\n", APPEND);
System.out.print("after APPEND:\n" + Files.readString(file));
Files.write(file, List.of("call Ravi", "review PR #42"));
System.out.print("after Files.write(lines):\n" + Files.readString(file));
System.out.println("size: " + Files.size(file));
}
}
Output (on Linux or macOS):
after two writeString calls:
renew domain
after APPEND:
renew domain
pay hosting
after Files.write(lines):
call Ravi
review PR #42
size: 24
What each call does:
- The first
writeStringcreatestodo.txtand writesbuy ink. - The second
writeStringreplaces it. With no options, the write methods useCREATE,TRUNCATE_EXISTINGandWRITE: create the file if necessary, otherwise erase the old content first.buy inkis gone. This default is the most common cause of accidentally lost data in file-writing code. APPENDopens the file and writes at the end, keeping the existing content. Note thatAPPENDalone requires the file to exist (NoSuchFileExceptionotherwise); combine it withCREATEto create the file on the first write, as the audit log example later does.Files.write(path, lines)writes each element followed by the platform's line separator (System.lineSeparator()), so you don't add\nyourself. Without options it also truncates, so the earlier lines disappear. The size is 24 bytes:call Ravi(9) +review PR #42(13) + two\n. On Windows, the separator is\r\nand the size would be 26.
writeString writes the string exactly as given, including whatever line endings it contains; Files.write(lines) and BufferedWriter.newLine() use the platform separator.
Writing Incrementally with BufferedWriter
When output is produced bit by bit — rows from a database, lines generated in a loop — keep one writer open instead of reopening the file for every piece.
import java.io.*;
import java.nio.file.*;
public class W3 {
public static void main(String[] args) throws IOException {
Path table = Path.of("multiplication.txt");
try (BufferedWriter out = Files.newBufferedWriter(table)) {
for (int i = 1; i <= 3; i++) {
out.write("7 x " + i + " = " + (7 * i));
out.newLine();
}
}
System.out.print(Files.readString(table));
Path report = Path.of("report.txt");
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(report))) {
pw.printf("%-10s %10s%n", "Course", "Revenue");
pw.printf("%-10s %,10.2f%n", "Java", 48250.0);
pw.printf("%-10s %,10.2f%n", "Django", 31900.5);
}
System.out.print(Files.readString(report));
}
}
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
Course Revenue
Java 48,250.00
Django 31,900.50
Files.newBufferedWriter(path)opens the file (creating or truncating it, by default) and returns aBufferedWriter. Text is collected in an in-memory buffer and written to disk in large blocks, which is much faster than many tiny writes.write(String)adds text;newLine()adds the platform's line separator.PrintWriterwraps any writer and addsprint,printlnandprintf, the same formatting methods you know fromSystem.out. Here%-10sleft-aligns the course name in 10 characters and%,10.2fright-aligns the amount in 10 characters with grouping separators and two decimals. The default locale determines the grouping separator; pass aLocaletoprintffor a fixed format.- try-with-resources closes the writer, which flushes the buffer and then closes the file.
A PrintWriter never throws IOException from its print methods. It records errors internally, and you must call checkError() to find out whether anything failed. For files where a failed write must be detected, write through the BufferedWriter directly, or call checkError() before closing.
Why Closing (Flushing) Matters
import java.io.*;
import java.nio.file.*;
public class W2 {
public static void main(String[] args) throws IOException {
Path forgot = Path.of("forgot-close.txt");
BufferedWriter w = Files.newBufferedWriter(forgot);
w.write("invoice total: 5630.75");
System.out.println("before close: " + Files.size(forgot) + " bytes");
w.close();
System.out.println("after close: " + Files.size(forgot) + " bytes");
}
}
Output:
before close: 0 bytes
after close: 22 bytes
The text was written into the writer's buffer, but nothing reached the file until close() flushed it. If a program forgets to close the writer — or crashes before it does — the file stays empty or ends with a cut-off last block. This is why output files should always be written inside try-with-resources.
flush()pushes buffered data to the operating system without closing the writer — useful for long-running writers such as a log that other programs read while it's being written.- Even after
flush()orclose(), the operating system may keep data in its own cache for a short time before it's physically on the disk. If data must survive a power failure (a database's transaction log, for example), it requires a forced sync, such asFileChannel.force(true)or theSYNC/DSYNCopen options. Normal application files don't need this.
Open Options Reference
Option (StandardOpenOption) | Effect |
|---|---|
WRITE | Open for writing |
CREATE | Create the file if it doesn't exist |
CREATE_NEW | Create the file; fail if it already exists |
TRUNCATE_EXISTING | Erase existing content when opening |
APPEND | Write at the end of the existing content |
SYNC / DSYNC | Force every write (content and metadata / content only) to the storage device |
DELETE_ON_CLOSE | Delete the file when it's closed (best effort) |
Some combinations are invalid: APPEND together with TRUNCATE_EXISTING, or APPEND with READ, throws IllegalArgumentException. When you pass any options, the defaults are no longer added, so Files.writeString(path, text, WRITE) alone fails if the file doesn't exist.
Practical Example: Exporting a CSV File
CSV looks trivial, but a value containing a comma, a quote or a line break breaks the format unless it's escaped. The rules (from RFC 4180): wrap such a value in double quotes, and double any quote inside it.
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
public class Csv {
record Customer(String name, String city, BigDecimal spent) { }
static String field(String value) {
if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
return "\"" + value.replace("\"", "\"\"") + "\"";
}
return value;
}
static void export(List<Customer> customers, Path target) throws IOException {
Files.createDirectories(target.toAbsolutePath().getParent());
try (BufferedWriter out = Files.newBufferedWriter(target, StandardCharsets.UTF_8)) {
out.write("name,city,spent\r\n");
for (Customer c : customers) {
out.write(field(c.name()) + "," + field(c.city()) + "," + c.spent().toPlainString() + "\r\n");
}
}
}
public static void main(String[] args) throws IOException {
List<Customer> customers = List.of(
new Customer("Asha Rao", "Chennai", new BigDecimal("12500.00")),
new Customer("Kumar, R.", "Coimbatore", new BigDecimal("830.50")),
new Customer("\"Max\" Store", "Madurai", new BigDecimal("99999.99")));
Path out = Path.of("export", "customers.csv");
export(customers, out);
System.out.print(Files.readString(out).replace("\r\n", "\n"));
}
}
Output:
name,city,spent
Asha Rao,Chennai,12500.00
"Kumar, R.",Coimbatore,830.50
"""Max"" Store",Madurai,99999.99
How it works:
fieldquotes a value only when needed.Kumar, R.contains a comma, so it becomes"Kumar, R."; without quotes a CSV reader would see four columns."Max" Storecontains quotes, so each"is doubled and the whole value is wrapped:"""Max"" Store".createDirectories(target.toAbsolutePath().getParent())makes sure theexportfolder exists.toAbsolutePath()is used because a bare file name such asPath.of("customers.csv")has no parent (getParent()returnsnull), while its absolute form always does.- The writer uses an explicit UTF-8 charset and CRLF line endings (
\r\n), as the CSV standard specifies and as Excel expects. The program prints the file with LF endings only to keep the console output tidy. BigDecimal.toPlainString()writes amounts without scientific notation, so values like1E+3can never appear in the export.- try-with-resources guarantees that the buffered data is flushed and the file is closed, even if writing a row fails.
For production exports with many edge cases, a library such as Apache Commons CSV or OpenCSV implements the same rules; the escaping logic above is exactly what they do.
Practical Example: Writing a File Atomically
If a program crashes or the server loses power halfway through Files.writeString(settings, json), the file may be left truncated — half old, half new, or empty — and the application may refuse to start next time. The standard technique to prevent this is to write to a temporary file in the same folder, then rename it over the original. A rename within one file system is atomic: other programs see either the complete old file or the complete new one, never something in between.
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;
public class Atomic {
static void saveAtomically(Path target, String content) throws IOException {
Path dir = target.toAbsolutePath().getParent();
Path tmp = Files.createTempFile(dir, target.getFileName() + ".", ".tmp");
try {
Files.writeString(tmp, content);
Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING);
} finally {
Files.deleteIfExists(tmp);
}
}
public static void main(String[] args) throws IOException {
Path settings = Path.of("settings.json");
saveAtomically(settings, "{\"theme\":\"light\",\"fontSize\":14}");
saveAtomically(settings, "{\"theme\":\"dark\",\"fontSize\":16}");
System.out.println(Files.readString(settings));
try (var files = Files.list(Path.of("."))) {
System.out.println("leftover temp files: " + files.filter(p -> p.toString().endsWith(".tmp")).count());
}
}
}
Output:
{"theme":"dark","fontSize":16}
leftover temp files: 0
Step by step:
- The temporary file is created in the same folder as the target (
createTempFile(dir, ...)), not in the system temp folder. An atomic rename only works within a single file system; moving across file systems is really a copy followed by a delete, which isn't atomic. - The new content is written completely to the temporary file. If this fails, the original
settings.jsonis untouched. Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING)replaces the original in one step. If the file system can't perform an atomic move, it throwsAtomicMoveNotSupportedExceptioninstead of silently doing something unsafe.finallyremoves the temporary file if anything went wrong. After a successful move,tmpno longer exists, sodeleteIfExistssimply returnsfalse.Files.listchecks that no.tmpfiles were left behind. It returns a stream holding an open directory handle, so it's closed with try-with-resources.
Editors, package managers and databases all use this pattern for files that must never be left half-written.
Practical Example: An Append-Only Audit Log
An audit log records who did what, and existing entries must never be modified. Appending with CREATE and APPEND fits exactly.
import java.io.*;
import java.nio.file.*;
import java.time.*;
import static java.nio.file.StandardOpenOption.*;
public class Audit {
static final Path LOG = Path.of("audit.log");
static void record(Instant at, String user, String action) throws IOException {
String line = at + " " + user + " " + action + System.lineSeparator();
Files.writeString(LOG, line, CREATE, APPEND);
}
public static void main(String[] args) throws IOException {
Instant t = Instant.parse("2026-11-15T03:50:00Z");
record(t, "asha", "LOGIN");
record(t.plusSeconds(42), "asha", "UPDATE course#17 price=4999");
record(t.plusSeconds(90), "ravi", "LOGIN");
System.out.print(Files.readString(LOG));
}
}
Output (on the first run):
2026-11-15T03:50:00Z asha LOGIN
2026-11-15T03:50:42Z asha UPDATE course#17 price=4999
2026-11-15T03:51:30Z ravi LOGIN
CREATE, APPENDcreates the file on the first call and appends on every later call. Running the program again adds three more lines instead of replacing the file.- Each entry is written in one call, with the line separator included in the same string. When a file is opened with
APPEND, each write is positioned at the current end of the file, so whole lines from separate calls don't overwrite each other. Building the complete line first, rather than writing the timestamp, user and action in separate calls, keeps each entry together. - Timestamps are
Instants in UTC, so entries from servers in different time zones sort correctly (Instant Class lesson).
Opening and closing the file for every entry is fine for occasional events. For high volumes — thousands of entries per second — keep one writer open, or use a logging framework such as Logback or Log4j 2, which add buffering, file rotation and safe concurrent access.