Java Reference
In-Depth Information
Code 12.20
Writing to a text file
using a try-with-
resource statement
public boolean createFile(String filename, int numEntries)
boolean success = false ;
try (FileWriter writer = new FileWriter(filename)) {
entry creation omitted
for ( int i = 0; i < numEntries; i++) {
writer.write( '\n' );
success = true ;
catch (IOException e) {
System.err.println( "There was a problem writing to " +
return success;
The resource is created in a new parenthesized section immediately after the try word. Once
the try statement is completed, the close method will be called automatically on this resource.
This version of the try statement is only appropriate for objects of classes that implement the
AutoCloseable interface, defined in the java.lang package. These will predominantly be
classes associated with input/output.
Exercise 12.44 Modify the world-of-zuul project so that it writes a script of user input to a text
file as a record of the game. There are several different ways that you might think of tackling this:
You could modify the Parser class to store each line of input in a list and then write out
the list at the end of the game. This will produce a solution that is closest to the basic pat-
tern we have outlined in the discussion above.
You could place all of the file handling in the Parser class so that, as each line is read,
it is written out immediately in exactly the same form as it was read. File opening, writ-
ing, and closing will all be separated in time from one another (or would it make sense to
open, write, and then close the file for every line that is written?).
You could place the file handling in the Game class and implement a toString method
in the Command class to return the String to be written for each command.
Consider each of these possible solutions in terms of responsibility-driven design and the han-
dling of exceptions, along with the likely implications for playing the game if it proves impos-
sible to write the script. How can you ensure that the script file is always closed when the end
of the game is reached? This is important to ensure that all of the output is actually written to
the external file system.
Search WWH ::

Custom Search