Part 08 / Topic 6 of 7
Putting it together: a to-do list that survives between runs
Every tool from this part, aimed at one job: load existing tasks from a file at startup, and save the full list back to that same file after every change, so the list is still there the next time the program runs.
// a plain class from Part 7
class Task(val text: String, var done: Boolean = false) {
fun toLine(): String = "${if (done) "done" else "pending"}|$text"
}
fun parseTaskLine(line: String): Task {
val parts = line.split("|", limit = 2)
require(parts.size == 2) { "expected \"status|text\", got \"$line\"" }
return Task(text = parts[1], done = parts[0] == "done")
}
fun loadTasks(file: File): MutableList<Task> {
if (!file.exists()) return mutableListOf()
return file.readLines().filter { it.isNotBlank() }.map { parseTaskLine(it) }.toMutableList()
}
fun saveTasks(file: File, tasks: List<Task>) {
file.bufferedWriter().use { writer ->
for (task in tasks) {
writer.write(task.toLine())
writer.newLine()
}
}
}
fun printTasks(tasks: List<Task>) {
if (tasks.isEmpty()) {
println("No tasks yet.")
return
}
for ((index, task) in tasks.withIndex()) {
val mark = if (task.done) "x" else " "
println("${index + 1}. [$mark] ${task.text}")
}
}
fun main() {
val todoFile = File("todos.txt")
val tasks = loadTasks(todoFile)
println("Loaded ${tasks.size} task(s) from ${todoFile.name}.")
while (true) {
println()
println("1. Add task")
println("2. List tasks")
println("3. Mark task done")
println("4. Remove task")
println("5. Exit")
print("Choose an option: ")
val choice = readlnOrNull()?.trim()
when (choice) {
"1" -> {
print("Task text: ")
val text = readlnOrNull()?.trim() ?: ""
if (text.isEmpty()) {
println("Task text cannot be empty.")
} else {
tasks.add(Task(text))
saveTasks(todoFile, tasks)
println("Added \"$text\".")
}
}
"2" -> printTasks(tasks)
"3" -> {
print("Task number to mark done: ")
val number = readlnOrNull()?.trim()?.toIntOrNull()
if (number == null || number < 1 || number > tasks.size) {
println("Enter a valid task number (1-${tasks.size}).")
} else {
tasks[number - 1].done = true
saveTasks(todoFile, tasks)
println("Marked \"${tasks[number - 1].text}\" done.")
}
}
"4" -> {
print("Task number to remove: ")
val number = readlnOrNull()?.trim()?.toIntOrNull()
if (number == null || number < 1 || number > tasks.size) {
println("Enter a valid task number (1-${tasks.size}).")
} else {
val removed = tasks.removeAt(number - 1)
saveTasks(todoFile, tasks)
println("Removed \"${removed.text}\".")
}
}
"5" -> {
println("Saved ${tasks.size} task(s) to ${todoFile.name}. Bye.")
break
}
else -> println("Invalid option, choose 1-5.")
}
}
}
A few design choices worth noticing:
saveTasksrewrites the entire file after every change, rather than trying to edit one line in place -- for a file this size, that's simpler and safer than in-place editing, and is the standard approach until a real database enters the picture (Stage 3)."done|Call plumber"uses|as the delimiter, not,-- a task's own text is far more likely to contain a comma than a pipe character, sidestepping section 5's naive-CSV problem for this particular format.loadTasksreturns an empty list (not an error) when the file doesn't exist yet -- the very first run of this program has nothing to load, and that's a normal case, not a failure.
Two separate runs, in the same directory, prove persistence actually works -- this is the real point of the exercise, not just that the menu loop works:
$ kotlinc 06_todo_list.kt -include-runtime -d todo.jar
$ printf '1\nBuy groceries\n1\nCall plumber\n1\nPay electricity bill\n2\n3\n2\n5\n' | java -jar todo.jar
Loaded 0 task(s) from todos.txt.
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task text: Added "Buy groceries".
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task text: Added "Call plumber".
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task text: Added "Pay electricity bill".
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: 1. [ ] Buy groceries
2. [ ] Call plumber
3. [ ] Pay electricity bill
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task number to mark done: Marked "Call plumber" done.
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Saved 3 task(s) to todos.txt. Bye.
$ cat todos.txt
pending|Buy groceries
done|Call plumber
pending|Pay electricity bill
A second, separate run of the same jar in the same directory -- a fresh process, started
after the first one already exited -- loads those 3 tasks straight from todos.txt, removes
one, adds another, and saves again:
$ printf '2\n4\n2\n2\n1\nSubmit tax documents\n2\n5\n' | java -jar todo.jar
Loaded 3 task(s) from todos.txt.
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: 1. [ ] Buy groceries
2. [x] Call plumber
3. [ ] Pay electricity bill
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task number to remove: Removed "Call plumber".
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: 1. [ ] Buy groceries
2. [ ] Pay electricity bill
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task text: Added "Submit tax documents".
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: 1. [ ] Buy groceries
2. [ ] Pay electricity bill
3. [ ] Submit tax documents
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Saved 3 task(s) to todos.txt. Bye.
$ cat todos.txt
pending|Buy groceries
pending|Pay electricity bill
pending|Submit tax documents
A third run shows the "mark done" menu option rejecting an out-of-range task number twice before exiting cleanly:
$ printf '3\n99\n3\nabc\n5\n' | java -jar todo.jar
Loaded 3 task(s) from todos.txt.
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task number to mark done: Enter a valid task number (1-3).
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Task number to mark done: Enter a valid task number (1-3).
1. Add task
2. List tasks
3. Mark task done
4. Remove task
5. Exit
Choose an option: Saved 3 task(s) to todos.txt. Bye.
"abc" fails toIntOrNull() and comes back null, which is handled by the exact same
number == null || number < 1 || number > tasks.size check as the out-of-range "99" -- one
guard covers both "not a number" and "a number, but the wrong one".
Full program: examples/06_todo_list.kt.
Done here? The practice set for Part 8 — including the solutions — is on the part page.