Capstone 2: saving tasks

A program that keeps its tasks in memory loses them when it stops. This lesson gives the task model a file: one task per line, four fields and a pipe between them, written with Files of lesson 106 and read with lesson 105. The round trip is the test, and it is the same idea as the CSV capstone of lesson 113 on a simpler format.

The line format

A line is id|status|priority|title, and the title is last so it may contain spaces. The pipe is not allowed in a title, and the compact constructor says so: a format with a separator that the data may contain needs either an escape or a rule, and a rule is the simpler of the two when the data is a title a person typed.

The four fields are the four components in an order the program chooses. The status is written as the name of the constant, which is what Status.valueOf reads back, and a name that is not a constant is the error of the last section.

Writing a task

toLine is a method of the record, so the format of a task lives with the task and not in the save method. The numbers are converted by string concatenation, which calls Integer.toString and Enum.toString.

Reading a task

fromLine is the other half and it is static, because there is no task yet. The split takes the line into four parts at most, so a title with a pipe in it would still be one field; then the three conversions, each of which can throw, are wrapped so that the message names the line number and not only the value:

line.split("[|]", 4) is a regular expression with a character class, because the pipe alone is the alternation operator of a pattern and would split the line into one character per field. The brackets say literally this character, which is the shortest way to write it without a backslash.

save and load

The two methods are the file part of lessons 105 and 106 and nothing more: a list of lines in, a list of tasks out. The whole program keeps the model of lesson 131 and adds the storage, so it builds and runs on its own:

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class TaskFile { enum Status { OPEN, DONE, DROPPED } record Task(int id, String title, Status status, int priority) { Task { if (title.isBlank()) { throw new IllegalArgumentException("empty title"); } if (title.contains("|")) { throw new IllegalArgumentException("title with a pipe: " + title); } } String toLine() { return id + "|" + status + "|" + priority + "|" + title; } static Task fromLine(String line, int number) { String[] parts = line.split("[|]", 4); if (parts.length != 4) { throw new IllegalArgumentException("line " + number + ": expected 4 fields, got " + parts.length); } try { return new Task(Integer.parseInt(parts[0]), parts[3], Status.valueOf(parts[1]), Integer.parseInt(parts[2])); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("line " + number + ": " + e.getMessage()); } } } static void save(Path file, List<Task> tasks) throws IOException { List<String> lines = new ArrayList<>(); for (Task task : tasks) { lines.add(task.toLine()); } Files.write(file, lines, StandardCharsets.UTF_8); } static List<Task> load(Path file) throws IOException { List<Task> tasks = new ArrayList<>(); List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8); for (int i = 0; i < lines.size(); i++) { if (!lines.get(i).isBlank()) { tasks.add(Task.fromLine(lines.get(i), i + 1)); } } return tasks; } public static void main(String[] args) throws IOException { Path file = Path.of("tasks.txt"); List<Task> tasks = List.of( new Task(1, "write the report", Status.OPEN, 2), new Task(2, "read the spec", Status.DONE, 1), new Task(3, "answer mail", Status.DROPPED, 3)); save(file, tasks); System.out.println("lines written: " + Files.readAllLines(file, StandardCharsets.UTF_8).size()); System.out.println(Files.readString(file, StandardCharsets.UTF_8).strip()); List<Task> loaded = load(file); System.out.println("loaded: " + loaded.size()); System.out.println("round trip: " + loaded.equals(tasks)); try { load(Path.of("missing.txt")); } catch (NoSuchFileException e) { System.out.println("missing: " + e.getFile()); } Files.writeString(file, "4|BROKEN|1|bad status\n", StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND); try { load(file); } catch (IllegalArgumentException e) { System.out.println("parse: " + e.getMessage()); } Files.delete(file); } }

javac -Xlint:all TaskFile.java
java TaskFile

lines written: 3
1|OPEN|2|write the report
2|DONE|1|read the spec
3|DROPPED|3|answer mail
loaded: 3
round trip: true
missing: missing.txt
parse: line 4: No enum constant TaskFile.Status.BROKEN

A missing file and a broken line

The last three lines are the two failures the storage has to survive. A file that is not there is a NoSuchFileException with the path, and a program that treats a missing file as an empty list catches it and continues with no tasks; a program that cannot work without the file lets it out, which is the choice of lesson 105.

The broken line is a status the enum does not know, and the message is the one valueOf threw, wrapped with the line number by fromLine. A reader of that report can open the file at line 4 and see the word, which is what a load failure has to give: the position and the value.

Exercises

  1. Add a field to the task and update both halves of the format.
  2. Make load skip a broken line and collect the errors in a list.
  3. Change the separator to a tab and run the program.
  4. Write the file in UTF-16 and read it again with the charset named both ways.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is the title the last field of a line?

    Answer

    So it may contain spaces, and a split into four parts keeps it whole

    The split with a limit stops at the fourth field, so the rest of the line is the title.

  2. What does line.split(&quot;[|]&quot;, 4) do?

    Answer

    Splits at most three times, giving four fields

    The limit is the number of results, and the class says the pipe is literal.

  3. What does Status.valueOf do with a name it does not know?

    Answer

    It throws IllegalArgumentException

    The lookup is at run time, and the exception is what fromLine wraps with the line number.

  4. What does this program print? import java.util.List; public class Q1 { public static void main(String[] args) { List<String> lines = List.of("a", "", "b"); int count = 0; for (String line : lines) { if (!line.isBlank()) { count++; } } System.out.println(count); System.out.println(lines.size()); } }

    Answer

    2 / 3

    The blank line is skipped by the count and still part of the list.

  5. Why does the compact constructor refuse a pipe in a title?

    Answer

    The pipe is the separator, and a title with one would add a field

    The format needs either an escape or a rule, and a rule on the data is the simpler choice here.

  6. What does fromLine do with a line of three fields?

    Answer

    It throws with the line number and the count it expected

    The check on the count comes before any conversion, and the message names both numbers.

  7. Why is toLine a method of the record?

    Answer

    The format of a task belongs with the task, not with the save method

    The two halves of a format sit together, which is what the round trip checks.

  8. What does this program print? public class Q2 { enum S { A } public static void main(String[] args) { try { System.out.println(S.valueOf("B")); } catch (IllegalArgumentException e) { System.out.println("unknown constant"); } } }

    Answer

    unknown constant

    The lookup fails at run time and the catch prints its line.

  9. What does Files.write(file, lines, charset) write between the lines?

    Answer

    A line separator after each line

    Each element is written as a line, which is why readAllLines gives the same list back.

  10. Why does the round trip compare the two lists of tasks?

    Answer

    A writer and a reader wrong in opposite ways can agree on a text and differ on the values

    The comparison of values is the check that both halves of the format agree.

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

Banner image