13 30 Singleton 2
This lesson picks up the Singleton class for our to-do list and finishes reading and writing the data file. Inside the load method we wrap the BufferedReader work in a try/finally block. The finally part checks if (br != null) and calls br.close(), which guarantees the file handle is released even if an exception is thrown during parsing.
Inside the try block we loop with while ((input = br.readLine()) != null) to read line by line. Each line holds three pieces of information separated by tab characters, so we call String[] itemPieces = input.split("\t"). From that array we pull the description from index 0, the details from index 1 and the deadline string from index 2.
Because we want a real date object rather than a raw string, we convert the deadline with LocalDate date = LocalDate.parse(itemPieces[2], formatter). We then build a new TodoItem with the description, details and parsed date, and add it to the todoItems list. After the loop the list is fully populated from disk.
Saving the to-do items back to the file
The second method, public void storeTodoItems() throws IOException, writes the list back out. We resolve the destination with Path path = Paths.get(filename) and open a BufferedWriter. Again we use try/finally and check if (bw != null) bw.close() to avoid leaks.
- Create an iterator over
todoItemsand loop withwhile (iter.hasNext()). - For each item, format three tab-separated fields with
String.format("%s\t%s\t%s", item.getDescription(), item.getDetails(), item.getDeadline().format(formatter)). - Call
bw.write(...)thenbw.newLine()so each item lands on its own line.
In the next video we move into the main class, override the stop() method and wire everything together so the application actually persists its data when it shuts down.