Learn Java · lesson 48 of 61 · about 10 minutes
Capstone: Errors and Testing
Save and load the duty board with java.nio, handle missing files, and check behaviour with small tests.
What you'll learn
- Write and read files with Files
- Handle IOException and missing files
- Write simple self-checking tests
A board that survives the night
Tomorrow's staff should see what's left, so the board is saved to duties.txt, one duty per line as priority|done|title, with the title last so it can contain anything, even a |. loadDuties() reads it back with Files.readAllLines, splitting each line into at most 3 parts, and a missing file loads as an empty list. Both methods declare throws IOException, and main catches it. Then a tiny check() method proves it all works, throwing an AssertionError if a missing file isn't empty or if the duties that come back aren't equal to the ones saved.
Files with java.nio
Files.writeString(Path.of("tasks.txt"), text)writes a fileFiles.readAllLines(path)reads it as a list of linesFiles.exists(path)checks first
File methods can throw IOException, a checked exception: Java forces you to either catch it or declare throws IOException.
Save, load and test
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
record Task(String title, int priority, boolean done) {}
public class Main {
static void save(Path path, List<Task> tasks) throws IOException {
StringBuilder sb = new StringBuilder();
for (Task t : tasks) sb.append(t.priority()).append('|').append(t.done()).append('|').append(t.title()).append('\n');
Files.writeString(path, sb.toString());
}
static List<Task> load(Path path) throws IOException {
List<Task> tasks = new ArrayList<>();
if (!Files.exists(path)) return tasks;
for (String line : Files.readAllLines(path)) {
String[] p = line.split("\\|", 3);
tasks.add(new Task(p[2], Integer.parseInt(p[0]), Boolean.parseBoolean(p[1])));
}
return tasks;
}
static void check(boolean ok, String name) {
if (!ok) throw new AssertionError("FAILED: " + name);
}
public static void main(String[] args) throws IOException {
Path file = Path.of("tasks.txt");
check(load(file).isEmpty(), "missing file loads as empty");
save(file, List.of(new Task("Feed Phoebe", 1, true), new Task("Write | test", 2, false)));
List<Task> loaded = load(file);
check(loaded.size() == 2, "two tasks come back");
check(loaded.get(0).done(), "done flag survives");
check(loaded.get(1).title().equals("Write | test"), "titles can contain the separator");
System.out.println("All tests passed");
}
}Output
All tests passedTip
Real projects use a test framework such as JUnit, but the idea is the same: run the code with known inputs and check the results automatically.
Equal all the way down
reloaded.equals(board.all()) compares two lists item by item, and each item is a record, whose equals compares every field. So one line checks that every duty came back with the same title, the same priority and the same done flag, in the same order. That's one of the best reasons to use records for data that gets saved.
Two lists of records
import java.util.List;
record Duty(String title, boolean done) {}
public class Main {
public static void main(String[] args) {
List<Duty> saved = List.of(new Duty("Lock up", true), new Duty("Mop", false));
List<Duty> loaded = List.of(new Duty("Lock up", true), new Duty("Mop", false));
List<Duty> changed = List.of(new Duty("Lock up", true), new Duty("Mop", true));
System.out.println(saved.equals(loaded) + " " + saved.equals(changed));
}
}Output
true falseNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.