Java Reference
In-Depth Information
To store the output of a program in a file, you use the
class
PrintWriter
. You declare
a
PrintWriter
variable and associate this variable with the destination, that is, the file
where the output will be stored. Suppose the output is to be stored in the file
prog.out
.
Consider the following statement:
PrintWriter outFile =
new
PrintWriter("prog.out");
This statement creates the
PrintWriter
object
outFile
and associates it with the file
prog.out
. (This statement assumes that the file
prog.out
is to be created in the directory
[subdirectory] where the main program is.)
If you want the output file to be stored, say, on a flash memory in drive H, then the
previous statement takes the following form:
PrintWriter outFile =
new
PrintWriter("h:\\prog.out");
You can now use the methods
print
,
println
, and
printf
with
outFile
in the same
way they have been used with the object
System.out
.
For example, the statement:
outFile.println("The paycheck is: $" + pay);
stores the output—
The paycheck is: $565.78
—in the file
prog.out
. This statement
assumes that the value of the variable
pay
is
565.78
.
Once the output is completed, Step 4 requires closing the file. You close the input and
output files by using the method
close
. For example, assuming that
inFile
and
outFile
are as declared before, the statements to close these files are:
inFile.close();
outFile.close();
Closing the output file ensures that the buffer holding the output will be emptied, that is,
the entire output generated by the program will be sent to the output file.
Step 3 requires that you create appropriate objects for file I/O. In the case of an input file, the
file must exist before the program executes. If the input file does not exist, then the statement
to associate the object with the input file fails and it
throws
a
FileNotFoundException
.At
this time, we will not require the program to handle this exception, so the method
main
will
also throw this exception. Therefore, the heading of the method
main
must contain an
appropriate command to throw a
FileNotFoundException
.
An output file does not have to exist before it is opened; if the output file does not exist,
the computer prepares an empty file for output. If the designated output file already exists, by
default, the old contents are erased (lost) when the file is opened. Note that if the program is not
able to create or access the output file, it throws a
FileNotFoundException
.
Search WWH ::
Custom Search