Java Reference
In-Depth Information
new
PrintWriter(
new
FileOutputStream(
"temp.txt"
,
true
));
If
temp.txt
does not exist, it is created. If
temp.txt
already exists, new data are
appended to the file.
19.4.2
FilterInputStream
/
FilterOutputStream
Filter streams
are streams that filter bytes for some purpose. The basic byte input stream pro-
vides a
read
method that can be used only for reading bytes. If you want to read integers,
doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class
enables you to read integers, doubles, and strings instead of bytes and characters.
FilterInputStream
and
FilterOutputStream
are the base classes for filtering data.
When you need to process primitive numeric types, use
DataInputStream
and
DataOutputStream
to filter bytes.
19.4.3
DataInputStream
/
DataOutputStream
DataInputStream
reads bytes from the stream and converts them into appropriate primitive
type values or strings.
DataOutputStream
converts primitive type values or strings into
bytes and outputs the bytes to the stream.
DataInputStream
extends
FilterInputStream
and implements the
DataInput
interface, as shown in Figure 19.9.
DataOutputStream
extends
FilterOutputStream
and implements the
DataOutput
interface, as shown in Figure 19.10.
«interface»
java.io.DataInput
InputStream
+readBoolean(): boolean
+readByte(): byte
+readChar(): char
+readFloat(): float
+readDouble(): double
+readInt(): int
+readLong(): long
+readShort(): short
+readLine(): String
+readUTF(): String
Reads a Boolean from the input stream.
Reads a byte from the input stream.
Reads a character from the input stream.
Reads a
float
from the input stream.
Reads a
double
from the input stream.
Reads an
int
from the input stream.
Reads a
long
from the input stream.
Reads a
short
from the input stream.
Reads a line of characters from input.
Reads a string in UTF format.
FilterInputStream
DataInputStream
+DataInputStream(
in: InputStream)
F
IGURE
19.9
DataInputStream
filters an input stream of bytes into primitive data type values and strings.
DataInputStream
implements the methods defined in the
DataInput
interface to read
primitive data type values and strings.
DataOutputStream
implements the methods defined
in the
DataOutput
interface to write primitive data type values and strings. Primitive values
are copied from memory to the output without any conversions. Characters in a string may be
written in several ways, as discussed in the next section.
Characters and Strings in Binary I/O
A Unicode character consists of two bytes. The
writeChar(char c)
method writes the
Unicode of character
c
to the output. The
writeChars(String s)
method writes the Uni-
code for each character in the string
s
to the output. The
writeBytes(String s)
method
writes the lower byte of the Unicode for each character in the string
s
to the output. The high
byte of the Unicode is discarded. The
writeBytes
method is suitable for strings that consist