Java Reference
In-Depth Information
Code 12.21
Reading from a text file
import java.io.*;
import java.util.*;
public class Responder
{
// Default responses to use if we don't recognize a word.
private List<String> defaultResponses;
// The name of the file containing the default responses.
private static final String FILE_OF_DEFAULT_RESPONSES =
"default.txt" ;
. . . other fields and methods omitted . . .
/**
* Build up a list of default responses from which we can pick
* if we don't know what else to say.
*/
private void fillDefaultResponses()
{
try {
BufferedReader reader = new BufferedReader(
new FileReader(FILE_OF_DEFAULT_RESPONSES));
String response = reader.readLine();
while (response != null ) {
defaultResponses.add(response);
response = reader.readLine();
}
reader.close();
}
catch (FileNotFoundException e) {
System.err.println( "Unable to open " +
FILE_OF_DEFAULT_RESPONSES);
}
catch (IOException e) {
System.err.println( "A problem was encountered reading " +
FILE_OF_DEFAULT_RESPONSES);
}
// Make sure we have at least one response.
if (defaultResponses.size() == 0) {
defaultResponses.add( "Could you elaborate on that?" );
}
}
}
As with output, the question arises as to what to do about any exceptions thrown during the
whole process. In this example, we have printed an error message and then provided at least
one response in case of a complete failure to read anything.
 
Search WWH ::




Custom Search