Java Reference
In-Depth Information
public
void
write
(
char
[]
text
)
throws
IOException
public
void
write
(
String
s
)
throws
IOException
public
void
write
(
String
s
,
int
offset
,
int
length
)
throws
IOException
public
abstract
void
flush
()
throws
IOException
public
abstract
void
close
()
throws
IOException
The
write(char[] text, int offset, int length)
method is the base method in
terms of which the other four
write()
methods are implemented. A subclass must
override at least this method as well as
flush()
and
close()
, although most override
some of the other
write()
methods as well in order to provide more efficient imple‐
mentations. For example, given a
Writer
object
w
, you can write the string “Network”
like this:
char
[]
network
=
{
'N'
,
'e'
,
't'
,
'w'
,
'o'
,
'r'
,
'k'
};
w
.
write
(
network
,
0
,
network
.
length
);
The same task can be accomplished with these other methods, as well:
w
.
write
(
network
);
for
(
int
i
=
0
;
i
<
network
.
length
;
i
++)
w
.
write
(
network
[
i
]);
w
.
write
(
"Network"
);
w
.
write
(
"Network"
,
0
,
7
);
All of these examples are different ways of expressing the same thing. The one you
choose to use in any given situation is mostly a matter of convenience and taste. How‐
ever, how many and which bytes are written by these lines depends on the encoding
w
uses. If it's using big-endian UTF-16, it will write these 14 bytes (shown here in hexa‐
decimal) in this order:
00 4E 00 65 00 74 00 77 00 6F 00 72 00 6B
On the other hand, if
w
uses little-endian UTF-16, this sequence of 14 bytes is written:
4E 00 65 00 74 00 77 00 6F 00 72 00 6B 00
If
w
uses Latin-1, UTF-8, or MacRoman, this sequence of seven bytes is written:
4E 65 74 77 6F 72 6B
Other encodings may write still different sequences of bytes. The exact output depends
on the encoding.
Writers may be buffered, either directly by being chained to a
BufferedWriter
or in‐
directly because their underlying output stream is buffered. To force a write to be com‐
mitted to the output medium, invoke the
flush()
method:
w
.
flush
();
The
close()
method behaves similarly to the
close()
method of
OutputStream
.
close()
flushes the writer, then closes the underlying output stream and releases any
resources associated with it:
public
abstract
void
close
()
throws
IOException