Java Reference
In-Depth Information
LISTING 11.7
continued
outFile.close();
System.out.println ("Output file has been created: " + file);
}
}
OUTPUT
Output file has been created: test.dat
The FileWriter class represents a text output file, but has minimal method
support for manipulating data. The PrintWriter class provides print and
println methods similar to the standard I/O PrintStream class.
The data that is contained in the file test.dat after the TestData program is
run might look like this:
85 90 93 15 82 79 52 71 70 98
74 57 41 66 22 16 67 65 24 84
86 61 91 79 18 81 64 41 68 81
98 47 28 40 69 10 85 82 64 41
23 61 27 10 59 89 88 26 24 76
33 89 73 36 54 91 42 73 95 58
19 41 18 14 63 80 96 30 17 28
24 37 40 64 94 23 98 10 78 50
89 28 64 54 59 23 61 15 80 88
51 28 44 48 73 21 41 52 35 38
Although we do not need to do so for the program to work, we have added a
layer in the file stream configuration to include a BufferedWriter . This addition
simply gives the output stream buffering capabilities, which makes the processing
more efficient. While buffering is not crucial in this situation, it is usually a good
idea when writing text files.
Note that in the TestData program, we have eliminated explicit exception
handling. That is, if something goes wrong, we simply allow the program to
terminate instead of specifically catching and handling the problem. Because all
IOExceptions are checked exceptions, we must include the throws clause on the
method header to indicate that they may be thrown. For each program, we must
carefully consider how best to handle the exceptions that may be thrown. This
requirement is especially important when dealing with I/O, which is fraught with
potential problems that cannot always be foreseen.
 
Search WWH ::




Custom Search