Java Reference
In-Depth Information
This
Scanner
object reads text from the file
input.txt
. You can use the
Scanner
methods (such as
next
,
nextLine
,
nextInt
, and
nextDouble
) to
read data from the input file.
When reading text files, use the
Scanner
class.
To write output to a file, you construct a
PrintWriter
object with the given file
name, for example
PrintWriter out = new PrintWriter("output.txt");
If the output file already exists, it is emptied before the new data are written into it. If
the file doesn't exist, an empty file is created.
When writing text files, use the
PrintWriter
class and the
print/println
methods.
Use the familiar
print
and
println
methods to send numbers, objects, and strings
to a
PrintWriter
:
out.println(29.95);
out.println(new Rectangle(5, 10, 15, 25));
out.println("Hello, World!");
The
print
and
println
methods convert numbers to their decimal string
representations and use the
toString
method to convert objects to strings.
498
499
When you are done processing a file, be sure to close the
Scanner
or
PrintWriter:
in.close();
out.close();
If your program exits without closing the
PrintWriter
, not all of the output may
be written to the disk file.
You must close all files When you are done processing them.