You have one more method to add to the ToDoList class, writeToDoFile(). This method writes the contents of the list model line by line into into a list file.
void writeToDoFile()
public void writeToDoFile() { FileWriter fileOutStream; PrintWriter dataOutStream; // carriage return and line feed constant String crlf = System.getProperties().getProperty("line.separator"); // write the file from the list try { fileOutStream = new FileWriter(FILE_NAME); dataOutStream = new PrintWriter(fileOutStream); // for every item in the list, write a line to the output file for (int i = 0; i < getDefaultListModel1().size(); i++) dataOutStream.write(getDefaultListModel1().getElementAt(i) + crlf); fileOutStream.close(); dataOutStream.close(); } catch (Throwable exc) { handleException(exc); } return; }
This code is similar to that for readToDoFile(). Before continuing with the next step, let's review the loop that actually writes lines to the file:
// for every item in the list, write a line to the output file for (int i = 0; i < getDefaultListModel1().size(); i++) dataOutStream.write(getDefaultListModel1().getElementAt(i) + crlf);
This loop goes through each item in the list model. Each item is appended with crlf (a String consisting of the line separator characters) and written to the file. The line separator characters force each item to be written on a separate line in the file.
Before continuing, pause and consider the line separator for a moment. Suppose you have never seen this before and you want to see how it works. You can use the Scrapbook window to test out a code fragment that exercises this part of your class.
To test the line separator code:
String crlf = System.getProperties().getProperty("line.separator"); System.out.println("Here is one line."+crlf+"And here's another line.");
Notice that the line separator splits the output so that it appears on separate lines. This simple example demonstrates how you can use the Scrapbook window to try out a piece of code quickly and conveniently.
![]() |
![]() |