Java Files.writeString
Files.writeString saves text to a file. Use APPEND when a new item belongs after the existing items.
A simple example
Files.writeString
- Start with Empty file and the letter A
- Do this Write the text, then read it
- Result "A"
Syntax
Files.writeString(path, text, StandardCharsets.UTF_8, StandardOpenOption.APPEND)
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep both items
A shopper adds an item after starting a list. The program must preserve what is already in the list and make the late addition visible when the list is displayed.
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
Path list = Files.createTempFile("shopping-", ".txt");
try {
Files.writeString(list, "Milk\n", StandardCharsets.UTF_8);
Files.writeString(list, "Rice\n", StandardCharsets.UTF_8, StandardOpenOption.APPEND);
System.out.print(Files.readString(list, StandardCharsets.UTF_8));
} finally {
Files.deleteIfExists(list);
}
}
}
Milk Rice
The first write sets the list contents. The second starts at the end, so Rice follows Milk. The example cleans up its temporary file.
Add a second handover to a shift log
Two assistants hand over the desk during one afternoon. The second update must leave the first person's note in place so the supervisor can reconstruct the sequence at closing time.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path log = desk.resolve("shift.txt");
Files.writeString(log, "Desk opened\n");
Files.writeString(log, "Keys returned", StandardOpenOption.APPEND);
System.out.println(Files.readString(log));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
Desk opened Keys returned
The first write creates the log. The append adds the second entry after the existing newline.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
What to watch for
With no open options, writeString creates a missing file or replaces an existing file’s contents. APPEND alone expects the file to exist.