← Java from Scratch
Lesson 57 of 88 · 10 XP
Writing to files
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
import java.io.FileWriter;
try (FileWriter w = new FileWriter("log.txt")) { // overwrite
w.write("the first line\n");
}
try (FileWriter w = new FileWriter("log.txt", true)) { // true — append to the end
w.write("the second line\n");
}
With Files — in one line:
Files.writeString(Path.of("a.txt"), "text");
Files.write(Path.of("a.txt"), List.of("line 1", "line 2")); // lines with line breaks
Files.writeString(Path.of("a.txt"), "more\n", StandardOpenOption.APPEND);
Without close() (or try-with-resources) part of the text may stay in the buffer and never reach the file.
Task. The input is lines of the form +text (append a line to todo.txt) and ! (clear the file). At the start
there's no file. Carry out the commands, then print the contents of the file (each line with a number, 1. …) and
total: N.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.