This section guides you through creating a method called readToDoFile(). This method reads the contents of a list file line by line and adds each line to the DefaultListModel1 instance.
void readToDoFile()
public void readToDoFile() {
FileReader fileInStream;
BufferedReader dataInStream;
String result;
try {
// read the file and fill the list
fileInStream = new FileReader(FILE_NAME);
dataInStream = new BufferedReader(fileInStream);
// clear the existing entries from the list
getDefaultListModel1().removeAllElements();
// for each line in the file create an item in the list
while ((result = dataInStream.readLine()) != null) {
if (result.length() != 0)
getDefaultListModel1().addElement(result);
}
fileInStream.close();
dataInStream.close();
} catch (Throwable exc) {
handleException(exc);
}
return;
}
Before continuing with the next task, let's review the code in this method:
FileReader fileInStream; BufferedReader dataInStream; String result;
try {
// read the file and fill the list
fileInStream = new FileReader(FILE_NAME);
dataInStream = new BufferedReader(fileInStream);
// clear the existing entries from the list
getDefaultListModel1().removeAllElements();
// for each line in the file create an item in the list
while ((result = dataInStream.readLine()) != null) {
if (result.length() != 0)
getDefaultListModel1().addElement(result);
}
fileInStream.close(); dataInStream.close();}
catch (Throwable exc) {
handleException(exc);
}
}
...
handleException(Throwable exc) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
System.out.println("--------- UNCAUGHT EXCEPTION ---------");
exception.printStackTrace(System.out);
}