How to Write to a File in Java

Naveen AnamaneniUpdated · 4 min read

Writing to a file in Java means storing text or bytes in a file on disk. For small amounts of data, Files.writeString and Files.write do everything in one line. For large or gradual output, Files.newBufferedWriter gives a BufferedWriter that writes efficiently. By default these methods create the file or overwrite it; open options such as StandardOpenOption.APPEND change that. In this lesson, you will learn all three ways and how to append.

Ways to Write

MethodBest for
Files.writeString(path, text)It is used to write one string (Java 11).
Files.write(path, lines)It writes a list of lines, each followed by a line break.
Files.write(path, bytes)It writes a byte array.
Files.newBufferedWriter(path)It returns a BufferedWriter for writing a lot of text gradually.
new FileWriter(file, true)It appends with the legacy API.

Open Options

OptionEffect
CREATECreate the file if it's missing
TRUNCATE_EXISTINGEmpty an existing file first
APPENDAdd to the end of the file
CREATE_NEWCreate, and fail if the file already exists

With no options, Java uses CREATE, TRUNCATE_EXISTING and WRITE, meaning "create or overwrite".

Example: Write, Overwrite and Append

Let's see an example that shows each behavior.

WriteDemo.java▶ Try it
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
 
public class WriteDemo {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("team.txt");
 
        Files.writeString(file, "Navika\n");
        Files.writeString(file, "Srihitha\n");
        System.out.print("After overwrite:\n" + Files.readString(file));
 
        Files.writeString(file, "Advitha\n", StandardOpenOption.APPEND);
        Files.write(file, List.of("Anamaneni"), StandardOpenOption.APPEND);
        System.out.print("After append:\n" + Files.readString(file));
    }
}
Output
After overwrite:
Srihitha
After append:
Srihitha
Advitha
Anamaneni

Explanation: The second writeString replaced Navika's line, because writing overwrites by default. APPEND adds to the end instead. Files.write with a list writes each element followed by a line break.

Example: Writing Many Lines with BufferedWriter

BigWrite.java▶ Try it
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class BigWrite {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("squares.csv");
        try (BufferedWriter w = Files.newBufferedWriter(file)) {
            w.write("n,square");
            w.newLine();
            for (int n = 1; n <= 1000; n++) {
                w.write(n + "," + (n * n));
                w.newLine();
            }
        }
        System.out.println("Lines: " + Files.readAllLines(file).size());
        System.out.println("Last: " + Files.readAllLines(file).get(1000));
    }
}
Output
Lines: 1001
Last: 1000,1000000

Explanation: Files.newBufferedWriter opens the file in UTF-8 with a buffer, so the 1,001 small writes become a few large disk writes. Try-with-resources closes the writer, which flushes the last buffered data to the file.

Common Mistakes

Calling writeString in a loop to build a file. Each call overwrites; append or use a BufferedWriter.

Forgetting to close a BufferedWriter. The last block never reaches the disk.

Using CREATE_NEW when the file may exist. It throws FileAlreadyExistsException.

Interview Corner

How do you append text to a file in Java?

With NIO.2, call Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND), or open Files.newBufferedWriter(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND) for many writes. With the legacy API, use new FileWriter(file, true). Without an append option, write methods truncate and overwrite the file.

Practice

  1. Easy: Write the multiplication table of 7 to seven.txt, one line per row.
  2. Harder: Write a logger method log(String message) that appends a line with the current time and the message to app.log, creating the file the first time.

Quick check: Writing files

4 questions
1What does Files.writeString do to an existing file by default?
2Which option adds to the end?
3Which is best for writing thousands of lines?
4What charset do NIO.2 write methods use by default?

Key Takeaways

Was this tutorial helpful?

Lesson 357 of 482