How to write text to a file
Short answer
Files.writeString() creates a file or overwrites an existing one:
void main() throws IOException {
Path file = Path.of("hello.txt");
Files.writeString(file, "Hello, file!\n");
IO.print(Files.readString(file));
}Output:
Hello, file!A list of lines
Files.write() writes each line of a list followed by a line break:
void main() throws IOException {
var lines = List.of("apples", "pears", "plums");
Files.write(Path.of("fruits.txt"), lines);
IO.println(Files.readAllLines(Path.of("fruits.txt")));
}Output:
[apples, pears, plums]Many writes
For writing in a loop use a BufferedWriter — it collects data and writes it to disk in large chunks:
void main() throws IOException {
Path file = Path.of("squares.txt");
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
for (int i = 1; i <= 3; i++) {
writer.write(i + " * " + i + " = " + i * i);
writer.newLine();
}
}
IO.print(Files.readString(file));
}Output:
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9Common mistake
Writing into a folder that does not exist. Java does not create folders for you:
void main() throws IOException {
Files.writeString(Path.of("reports/2026/march.txt"), "data");
}Output:
Exception in thread "main" java.nio.file.NoSuchFileException: reports\2026\march.txtCreate the folders first: Files.createDirectories(file.getParent()).
Functions used in this recipe
- Files.writeString() — Writes a string to a file, creating or overwriting it.