How to Write to a File in Java
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
| Method | Best 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
| Option | Effect |
|---|---|
CREATE | Create the file if it's missing |
TRUNCATE_EXISTING | Empty an existing file first |
APPEND | Add to the end of the file |
CREATE_NEW | Create, 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.
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));
}
}After overwrite:
Srihitha
After append:
Srihitha
Advitha
AnamaneniExplanation: 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
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));
}
}Lines: 1001
Last: 1000,1000000Explanation: 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
- Easy: Write the multiplication table of 7 to
seven.txt, one line per row. - Harder: Write a logger method
log(String message)that appends a line with the current time and the message toapp.log, creating the file the first time.
Key Takeaways
Was this tutorial helpful?