![]() |
![]() |
You have one more method to add to the ToDoList class. This method, called writeToDoFile, writes an output file. Let's review what this method is supposed to do:
Here are the detailed steps for creating this method:
This specifies a method that takes 3 arguments.
dirName | The name of the directory that holds the file to be written |
fileName | The name of the file to be written |
fillList | The DefaultListModel object in the interface containing the items to be written to the file |
public void writeToDoFile(File dirName, File fileName, DefaultListModel fillList) { FileWriter fileOutStream = null; PrintWriter dataOutStream; // carriage return and line feed constant String crlf = System.getProperties().getProperty("line.separator"); // if valid directory and filenames passed, write the file from the list if ((dirName != null) && (fileName != null)) { try { fileOutStream = new FileWriter(fileName); } catch (IOException e) { System.err.println ("IO exception opening To-Do File " +fileName); return; } dataOutStream = new PrintWriter(fileOutStream); // for every item in the list, write a line to the output file for (int i = 0; i < fillList.getSize(); i++) { try { dataOutStream.write(fillList.get(i)+crlf); } catch (Exception e) { System.err.println ("Exception writing To-Do File " +fileName);} } try { fileOutStream.close(); dataOutStream.close(); } catch (IOException e) { System.err.println ("IO exception closing To-Do File " +fileName);} } else { System.err.println ("Null file name and/or directory writing To-Do File"); } return; }
Select Save from the Edit menu to save your changes and recompile.
This code is similar to the code for readToDoFile. Before continuing with the next step, let's review the loop that actually writes lines to the file:
for (int i = 0; i < fillList.getSize(); i++) { try { dataOutStream.write(fillList.get(i)+crlf); } catch (Exception e) { System.err.println("Exception writing To-Do File " +fileName);} }
This loop goes through each item in fillList. 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, let's 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.
![]() |
![]() |