Java Reference
In-Depth Information
public boolean log(String msg)
{
if (fw == null)
return false;
try
{
fw.write(msg+LINE_SEPARATOR);
}
catch (IOException ioe)
{
return false;
}
return true;
}
}
Listing 8-19 refactors Listing 3-20 to support FileWriter by making changes to
each of the connect() , disconnect() , and log() methods:
connect() attemptstoinstantiate FileWriter ,whoseinstanceissavedin
fw upon success; otherwise, fw continues to store its default null reference.
disconnect() attempts to close the file by calling FileWriter 's
close() method, but only when fw doesn't contain its default null reference.
log() attempts to write its String argument to the file by calling
FileWriter 's void write(String str) method, but only when fw
doesn't contain its default null reference.
connect() 's catch clause specifies IOException instead of
FileNotFoundException because FileWriter 's constructors throw IOEx-
ception whentheycannotconnecttoexistingnormalfiles; FileOutputStream 's
constructors throw FileNotFoundException .
log() 's write(String) methodappendsthe line.separator value(which
Iassignedtoaconstantforconvenience)tothestringbeingoutputinsteadofappending
\n , which would violate portability.
FileReader isaconvenienceclassforreadingcharactersfromfiles.Itsubclasses
InputStreamReader , and its constructors call InputStreamRead-
Search WWH ::




Custom Search