AI Hints
Home›Java Tutorial›Project: Saving Tasks, Loading Tasks and Reports with Streams
Java · Lesson 116 of 120

Project: Loading Tasks

Read them back.

⏱ 2 min read▶ Video at 2:27:16🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Loading does the opposite of saving. Read each line, split it into its parts, and build a task again.

  • The reverse of save
  • Split each line
  • Build tasks again

TaskStore: load

If the file doesn't exist yet, we return an empty list. That's the first run. Split, with a limit of four, makes at most four parts. So any semicolons inside the title stay in the title. Then we parse the numbers, and the boolean, and create the task.

Main.javajava
    public List<Task> load() throws IOException {
        List<Task> out = new ArrayList<>();
        if (!Files.exists(file)) return out;
        for (String line : Files.readAllLines(file)) {
            String[] p = line.split(";", 4);
            int id = Integer.parseInt(p[0]), prio = Integer.parseInt(p[1]);
            out.add(new Task(id, p[3], prio, Boolean.parseBoolean(p[2])));
        }
        return out;
    }

Restoring ids

TaskList gets one new method, restore. It adds a loaded task as it is, and moves next id past it. So new tasks never reuse an old id.

keyvalue
restore(t)add a loaded task
nextIdmax(nextId, t.id() + 1)
Resultno duplicate ids
Added toTaskList.java

Loading for real

We load the saved file, and restore each task into the list. Then we add a new task. A missing file just gives zero tasks. Run it. All five tasks are back. The new task gets id six, not one. And the missing file gives zero, with no crash.

Main.javajava
public class Main {
    public static void main(String[] args) throws Exception {
        TaskStore store = new TaskStore("tasks.txt");
        TaskList list = new TaskList();
        store.load().forEach(list::restore);
        list.all().forEach(System.out::println);
        Task added = list.add("Buy milk", 2);
        System.out.println("New task got id " + added.id());
        int none = new TaskStore("nothing.txt").load().size();
        System.out.println(none + " tasks in a missing file");
    }
}
Output
 1 [ ] !!! Pay rent
 2 [x] !   Water plants
 3 [ ] !!  Book dentist; maybe Friday
 4 [x] !!  Email Sam
 5 [ ] !!! Finish report
New task got id 6
0 tasks in a missing file
Also uses Task.java
public record Task(int id, String title, int priority, boolean done) {
    public Task {
        if (title.isBlank()) throw new IllegalArgumentException("Title can't be empty");
        if (priority < 1 || priority > 3) throw new IllegalArgumentException("1-3 only");
    }

    public Task complete() {
        return new Task(id, title, priority, true);
    }

    @Override
    public String toString() {
        String box = done ? "[x]" : "[ ]";
        return String.format("%2d %s %-3s %s", id, box, "!".repeat(priority), title);
    }
}
Also uses TaskList.java
import java.util.*;
public class TaskList {
    private final List<Task> tasks = new ArrayList<>();
    private int nextId = 1;

    public Task add(String title, int priority) {
        Task t = new Task(nextId++, title, priority, false);
        tasks.add(t);
        return t;
    }
    public void complete(int id) {
        tasks.replaceAll(t -> t.id() == id ? t.complete() : t);
    }
    public boolean remove(int id) { return tasks.removeIf(t -> t.id() == id); }
    public List<Task> all() { return List.copyOf(tasks); }
    public void restore(Task t) { tasks.add(t); nextId = Math.max(nextId, t.id() + 1); }
}
Also uses TaskStore.java
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class TaskStore {
    private final Path file;
    public TaskStore(String name) { file = Path.of(name); }

    public void save(List<Task> tasks) throws IOException {
        List<String> lines = new ArrayList<>();
        for (Task t : tasks) {
            lines.add(t.id() + ";" + t.priority() + ";" + t.done() + ";" + t.title());
        }
        Files.write(file, lines);
    }

    public List<Task> load() throws IOException {
        List<Task> out = new ArrayList<>();
        if (!Files.exists(file)) return out;
        for (String line : Files.readAllLines(file)) {
            String[] p = line.split(";", 4);
            int id = Integer.parseInt(p[0]), prio = Integer.parseInt(p[1]);
            out.add(new Task(id, p[3], prio, Boolean.parseBoolean(p[2])));
        }
        return out;
    }
}
Also uses tasks.txt
1;3;false;Pay rent
2;1;true;Water plants
3;2;false;Book dentist; maybe Friday
4;2;true;Email Sam
5;3;false;Finish report

Summary

Load reads each line, splits it into four parts, and builds a task. Restore keeps the ids unique. Next, reports, with streams.

Key takeaways
  • split(";", 4)
  • Missing file → empty
  • restore keeps ids
Next up: Project: Reports with Streams — useful summaries