Writing files
Writing a text file is one method, and the interesting part is what happens when the file is already there: replace it, add to its end, or refuse. Those three are StandardOpenOption values, and the program below writes the same file three ways and prints the size after each.
writeString and the open options
With no options, writeString creates the file or replaces its contents. APPEND adds at the end, and TRUNCATE_EXISTING is the replace that the default already does, written out:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class Write {
public static void main(String[] args) throws IOException {
Path file = Path.of("log.txt");
Files.writeString(file, "first\n", StandardCharsets.UTF_8);
System.out.println("after first: " + Files.size(file) + " bytes");
Files.writeString(file, "second\n", StandardCharsets.UTF_8, StandardOpenOption.APPEND);
System.out.println("after append: " + Files.size(file) + " bytes");
Files.writeString(file, "third\n", StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);
System.out.println("after truncate: " + Files.size(file) + " bytes");
Files.writeString(file, "fourth\n", StandardCharsets.UTF_8, StandardOpenOption.APPEND);
System.out.print(Files.readString(file, StandardCharsets.UTF_8));
System.out.println("lines: " + Files.readAllLines(file, StandardCharsets.UTF_8).size());
Files.delete(file);
}
}
javac -Xlint:all Write.java
java Write
after first: 6 bytes
after append: 13 bytes
after truncate: 6 bytes
third
fourth
lines: 2
Append and truncate
The numbers are the whole story: first\n is six bytes, second\n makes thirteen, and the truncate brings the file back to six while replacing the word. The second append then adds a fourth line, and the read returns the two lines that survived.
A log is the case for APPEND: a program that writes one line per run must not delete the run before. A report is the case for the default: the file is the current answer, and an old version of it is worse than nothing. The mistake to avoid is an append where a replace was meant, which shows up as a file that grows every time the program runs.
Directories
createDirectories creates every missing folder of a path, so a program does not need a check per level and does not fail when the folder is already there. The program makes a temporary tree, writes a file inside and removes the tree at the end:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
public class Dirs {
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("demo");
Path nested = root.resolve("reports").resolve("2026");
Files.createDirectories(nested);
System.out.println("exists: " + Files.isDirectory(nested));
Path file = nested.resolve("report.txt");
Files.writeString(file, "one\ntwo\n", StandardCharsets.UTF_8);
System.out.println("file inside: " + Files.exists(file));
System.out.println("names in 2026: " + Files.list(nested).count());
long files = Files.walk(root).filter(Files::isRegularFile).count();
System.out.println("files in the tree: " + files);
try (var paths = Files.walk(root)) {
paths.sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
System.out.println("removed: " + !Files.exists(root));
}
}
javac -Xlint:all Dirs.java
java Dirs
exists: true
file inside: true
names in 2026: 1
files in the tree: 1
removed: true
The path is built with resolve, which is the next lesson's subject, and the removal walks the tree in reverse order so that a folder is deleted after its contents. Files.delete refuses a folder that is not empty, which is why the sort is there; a Files.walk returns the root first and its children after, so the reverse is the order that works.
Copy and move
copy and move are the two operations that read and write at once, and both refuse to replace an existing target unless the option says so:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class Copy {
public static void main(String[] args) throws IOException {
Path source = Path.of("a.txt");
Path copy = Path.of("b.txt");
Path moved = Path.of("c.txt");
Files.writeString(source, "payload", StandardCharsets.UTF_8);
Files.copy(source, copy);
System.out.println("copy exists: " + Files.exists(copy));
System.out.println("same text: " + Files.readString(copy, StandardCharsets.UTF_8).equals("payload"));
try {
Files.copy(source, copy);
} catch (java.nio.file.FileAlreadyExistsException e) {
System.out.println("second copy: " + e.getClass().getSimpleName());
}
Files.copy(source, copy, StandardCopyOption.REPLACE_EXISTING);
System.out.println("replaced: " + Files.size(copy));
Files.move(copy, moved);
System.out.println("moved: " + (!Files.exists(copy) && Files.exists(moved)));
Files.delete(source);
Files.delete(moved);
System.out.println("cleaned: " + (!Files.exists(source) && !Files.exists(moved)));
}
}
javac -Xlint:all Copy.java
java Copy
copy exists: true
same text: true
second copy: FileAlreadyExistsException
replaced: 7
moved: true
cleaned: true
The second copy is the interesting line: the default refuses to overwrite, which is the safe choice, and REPLACE_EXISTING is how a program asks for the other one. A move in the same file system renames, and a move to another one copies and deletes; the method does not make the difference visible, which matters when the destination is on a network share.
Rules for writing
Name the charset, as lesson 105 does for reading. Decide on purpose between replace and append, and say so in the code with the option. Create the folder before the file, with createDirectories on the parent. Treat a write as something that can fail, because the disk can be full or read-only, and a program that ignores that ends with a file it never finished. And when the program writes a temporary file that another part will use, write it under a name of its own and move it into place, so a reader never sees a half-written file.
The last rule is the one a server needs and a script does not. The move is atomic in the same file system, which is why the pattern is called write-and-rename, and it is the difference between a configuration that is old or new and one that is broken for a moment.
Exercises
- Write the numbers one to five to a file, one per line, and read them back with a sum.
- Append a timestamp line to a file and print the number of bytes after each run of your program twice.
- Create a folder three levels deep under a temporary root and list the names at each level.
- Copy a file into a folder that does not exist and report the exception.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a
writeStringwith no options do to an existing file?Answer
It replaces the contents
The default creates the file or truncates it, which is the replace the option names.
-
Which option adds to the end of a file?
Answer
StandardOpenOption.APPEND
APPEND keeps the existing bytes and writes after them.
-
What does
createDirectoriesdo when the folder is already there?Answer
It does nothing and returns the path
The method creates the missing levels only, which is why it is safe to call every run.
-
What does this program print?
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; public class Q1 { public static void main(String[] args) throws IOException { Path file = Path.of("w.txt"); Files.writeString(file, "aa", StandardCharsets.UTF_8); Files.writeString(file, "bb", StandardCharsets.UTF_8, StandardOpenOption.APPEND); System.out.println(Files.readString(file, StandardCharsets.UTF_8)); System.out.println(Files.size(file)); Files.delete(file); } }Answer
aabb / 4
The append keeps the first two bytes, and the file is four bytes of aabb.
-
Why does moving the tree need a reverse order?
Answer
A folder can only be deleted when it is empty
Files.delete on a folder with contents throws, so the children go first.
-
What does
Files.copydo when the target exists and no option is given?Answer
It throws FileAlreadyExistsException
The safe default refuses to overwrite, and REPLACE_EXISTING asks for the other behaviour.
-
Why write a temporary file and move it into place?
Answer
A reader then sees either the old file or the new one, never a half-written one
The move within one file system is atomic, which is what the pattern is for.
-
What does this program print?
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; public class Q2 { public static void main(String[] args) throws IOException { Path file = Path.of("x.txt"); Files.writeString(file, "one", StandardCharsets.UTF_8); Files.writeString(file, "two", StandardCharsets.UTF_8); System.out.println(Files.size(file)); Files.delete(file); } }Answer
3
The second write replaces the first, so the file holds the three bytes of two.
-
What does this program print?
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; public class Q3 { public static void main(String[] args) throws IOException { Path file = Path.of("y.txt"); Files.writeString(file, "abc", StandardCharsets.UTF_8); Files.writeString(file, "de", StandardCharsets.UTF_8); System.out.println(Files.size(file)); Files.delete(file); } }Answer
2
The second write replaces the three bytes with two, so the size is two.
-
Which call creates a folder and every missing parent?
Answer
Files.createDirectories
createDirectory needs the parent to exist, and createDirectories builds the chain.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev