Java Write Files

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 137 of 306

Choosing a Way to Write a File

MethodWritesKeeps a file open for multiple writes?Best for
Files.writeString(path, text, options...)One StringNoSmall text output: a JSON document, a report
Files.write(path, lines, options...)An Iterable of lines, each followed by a line separatorNoA list of lines you already have in memory
Files.write(path, bytes, options...)A byte[]NoSmall binary data
Files.newBufferedWriter(path, options...)Text, piece by pieceYesLarge or incremental output: exports, generated files
PrintWriter around a writerFormatted text (printf, println)YesReports and aligned tables
Files.newOutputStream(path, options...)Bytes, piece by pieceYesLarge 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:

  1. The first writeString creates todo.txt and writes buy ink.
  2. The second writeString replaces it. With no options, the write methods use CREATE, TRUNCATE_EXISTING and WRITE: create the file if necessary, otherwise erase the old content first. buy ink is gone. This default is the most common cause of accidentally lost data in file-writing code.
  3. APPEND opens the file and writes at the end, keeping the existing content. Note that APPEND alone requires the file to exist (NoSuchFileException otherwise); combine it with CREATE to create the file on the first write, as the audit log example later does.
  4. Files.write(path, lines) writes each element followed by the platform's line separator (System.lineSeparator()), so you don't add \n yourself. 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\n and 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 a BufferedWriter. 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.
  • PrintWriter wraps any writer and adds print, println and printf, the same formatting methods you know from System.out. Here %-10s left-aligns the course name in 10 characters and %,10.2f right-aligns the amount in 10 characters with grouping separators and two decimals. The default locale determines the grouping separator; pass a Locale to printf for 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() or close(), 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 as FileChannel.force(true) or the SYNC/DSYNC open options. Normal application files don't need this.

Open Options Reference

Option (StandardOpenOption)Effect
WRITEOpen for writing
CREATECreate the file if it doesn't exist
CREATE_NEWCreate the file; fail if it already exists
TRUNCATE_EXISTINGErase existing content when opening
APPENDWrite at the end of the existing content
SYNC / DSYNCForce every write (content and metadata / content only) to the storage device
DELETE_ON_CLOSEDelete 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:

  1. field quotes 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" Store contains quotes, so each " is doubled and the whole value is wrapped: """Max"" Store".
  2. createDirectories(target.toAbsolutePath().getParent()) makes sure the export folder exists. toAbsolutePath() is used because a bare file name such as Path.of("customers.csv") has no parent (getParent() returns null), while its absolute form always does.
  3. 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.
  4. BigDecimal.toPlainString() writes amounts without scientific notation, so values like 1E+3 can never appear in the export.
  5. 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:

  1. 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.
  2. The new content is written completely to the temporary file. If this fails, the original settings.json is untouched.
  3. 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 throws AtomicMoveNotSupportedException instead of silently doing something unsafe.
  4. finally removes the temporary file if anything went wrong. After a successful move, tmp no longer exists, so deleteIfExists simply returns false.
  5. Files.list checks that no .tmp files 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, APPEND creates 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Write Files and get answers drawn from it.

Signed-in readers only.