Java Reference
In-Depth Information
Display 10.2
Some Methods of the Class
PrintWriter
(part 2 of 2)
public void
println(
Argument
)
The
Argument
can be a string, character, integer, floating-point number,
boolean
value, or any com-
bination of these, connected with
+
signs. The
Argument
can also be any object, although it will not
work as desired unless the object has a properly defined
toString()
method. The
Argument
is out-
put to the file connected to the stream. After the
Argument
has been output, the line ends, and so
the next output is sent to the next line.
public void
print(
Argument
)
This is the same as
println
, except that this method does not end the line, so the next output will
be on the same line.
public
PrintWriter printf(
Arguments
)
This is the same as
System.out.printf
, except that this method sends output to a text file rather
than to the screen. It returns the calling object. However, we have always used
printf
as a
void
method.
public void
close()
Closes the stream's connection to a file. This method calls
flush
before closing the file.
public void
flush()
Flushes the output stream. This forces an actual physical write to the file of any data that has been
buffered and not yet physically written to the file. Normally, you should not need to invoke
flush
.
When your program is finished writing to a file, it should
close
the stream con-
nected to that file. In Display 10.1, the stream connected to the file
stuff.txt
is
closed with the statement
outputStream.close();
The class
PrintWriter
, and every other class for file output or file input streams, has a
method named
close
. When this method is invoked, the system releases any resources
used to connect the stream to the file and does any other housekeeping that is needed.
If your program does not close a file before the program ends, Java will close it for you
when the program ends, but it is safest to close the file with an explicit call to
close
.
Output streams connected to files are often
buffered
, which means that, rather
than physically writing every instance of output data as soon as possible, the data is
saved in a temporary location, known as a
buffer
; when enough data is accumulated
in this temporary location, it is physically written to the file. This can add to efficiency,
since physical writes to a file can be slow. The method
flush
causes a physical write to
buffered
buffer