Java Reference
In-Depth Information
When a file has been opened successfully, then the writer's write methods can be used to store
characters—often in the form of strings—into the file. Any attempt to write could fail, even if
the file has been opened successfully. Such failures are rare, but still possible.
Once all output has been written, it is important to formally close the file. This ensures that all the
data really has been written to the external file system, and it often has the effect of freeing some
internal or external resources. Once again, on rare occasions the attempt to close the file could fail.
The basic pattern that emerges from the above discussion looks like this:
try {
FileWriter writer = new FileWriter(" ... name of file ... ");
while( there is more text to write ) {
...
writer.write( next piece of text );
...
}
writer.close();
}
catch(IOException e) {
something went wrong in dealing with the file
}
The main issue that arises is how to deal with any exceptions that are thrown during the three stages.
An exception thrown when attempting to open a file is really the only one it is likely to be possible to
do anything about, and only then if there is some way to generate an alternative name to try instead.
As this will usually require the intervention of a human user of the application, the chances of deal-
ing with it successfully are obviously application- and context-specific. If an attempt to write to the
file fails, then it is unlikely that repeating the attempt will succeed. Similarly, failure to close a file is
not usually worth a further attempt. The consequence is likely to be an incomplete file.
An example of this pattern can be seen in Code 12.19. The LogfileCreator class in the
weblog-analyzer project includes a method to write a number of random log entries to a file
whose name is passed as a parameter to the createFile method. This uses two different
write methods: one to write a string and one to write a character. After writing out the text of
the entry as a string, we write a newline character so that each entry appears on a separate line.
Code 12.19
Writing to a text file
/**
* Create a file of random log entries.
* @param filename The file to write.
* @param numEntries How many entries.
* @return true if successful, false otherwise.
*/
public boolean createFile(String filename, int numEntries)
{
boolean success = false ;
try {
FileWriter writer = new FileWriter(filename);
LogEntry[] entries = new LogEntry[numEntries];
 
Search WWH ::




Custom Search