Java Reference
In-Depth Information
Buffered
output streams behave similarly. When a
write
fills the buffer,
the destination stream's
write
is invoked to empty the buffer. This buf-
fering can turn many small
write
requests on the
Buffered
stream into a
single
write
request on the underlying destination.
Here is how to create a buffered output stream to write bytes to a file:
new BufferedOutputStream(new FileOutputStream(path));
You create a
FileOutputStream
with the path, put a
BufferedOutputStream
in front of it, and use the buffered stream object. This scheme enables
you to buffer output destined for the file.
You must retain a reference to the
FileOutputStream
object if you want to
invoke methods on it later because there is no way to obtain the down-
stream object from a
Filter
stream. However, you should rarely need
to work with the downstream object. If you do keep a reference to a
downstream object, you must ensure that the first upstream object is
flushed before operating on the downstream object because data writ-
ten to upper streams may not have yet been written all the way down-
stream. Closing an upstream object also closes all downstream objects,
so a retained reference may cease to be usable.
The
Buffered
character streams also understand lines of text. The
newLine
method of
BufferedWriter
writes a line separator to the stream. Each sys-
tem defines what constitutes a line separator in the system
String
prop-
erty
line.separator
, which need not be a single character. You should
use
newLine
to end lines in text files that may be read by humans on the
local system (see "
System Properties
" on page
663
)
.
The method
readLine
in
BufferedReader
returns a line of text as a
String
.
The method
readLine
accepts any of the standard set of line separators:
line feed (
\n
), carriage return (
\r
), or carriage return followed by line
feed (
\r\n
). This implies that you should never set
line.separator
to use
any other sequence. Otherwise, lines terminated by
newLine
would not
be recognized by
readLine
. The string returned by
readLine
does not in-
clude the line separator. If the end of stream is encountered before a