Java Reference
In-Depth Information
Code 12.19
continued
Writing to a text file
for ( int i = 0; i < numEntries; i++) {
entries[i] = createEntry();
}
Arrays.sort(entries);
for ( int i = 0; i < numEntries; i++) {
writer.write(entries[i].toString());
writer.write( '\n' );
}
writer.close();
success = true ;
}
catch (IOException e) {
System.err.println( "There was a problem writing to " +
filename);
}
return success;
}
One problem with the pattern shown in Code 12.19 is that failure, once the file has been
opened, will leave it open. This wastes a small amount of program resource but, more impor-
tantly, leaves the file system in a misleading position, because it must assume that the program
is still using the file. See the following section for a way to deal with error situations as a result
of changes introduced in Java 7.
12.9.4
The try-with-resource statement
Java 7 introduced a feature to the try statement for dealing with situations where a resource
such as an open file should definitely be closed once it is finished with—whether the use of it
completed successfully or not. This form is called try with resource or automatic resource man-
agement (ARM). Code 12.20 shows its use with an alternative version of Code 12.19, which
you can find in the project weblog-analyzer-v7 .
Code 12.20
Writing to a text file
using a try-with-
resource statement
/**
* Create a file of random log entries.
* @param filename The file to write.
* @param numEntries How many entries.
* @return true if successful, false otherwise.
*/
 
Search WWH ::




Custom Search