Java Reference
In-Depth Information
Data Streams
If you need to work with data that isn't represented as bytes or characters, you can use
data input and data output streams. These streams filter an existing byte stream so that
each of the following primitive types can be read or written directly from the stream:
boolean
,
byte
,
double
,
float
,
int
,
long
, and
short
.
15
A data input stream is created with the
DataInputStream(
InputStream
)
constructor.
The argument should be an existing input stream such as a buffered input stream or a file
input stream.
A data output stream requires the
DataOutputStream(
OutputStream
)
constructor, which
indicates the associated output stream.
The following list indicates the read and write methods that apply to data input and out-
put streams, respectively:
readBoolean()
,
writeBoolean(
boolean
)
n
readByte()
,
writeByte(
integer
)
n
readDouble()
,
writeDouble(
double
)
n
readFloat()
,
writeFloat(
float)
n
readInt()
,
writeInt(
int
)
n
readLong()
,
writeLong(
long
)
n
readShort()
,
writeShort(
int
)
n
Each input method returns the primitive data type indicated by the name of the method.
For example, the
readFloat()
method returns a
float
value.
There also are
readUnsignedByte()
and
readUnsignedShort()
methods that read in
unsigned
byte
and
short
values. These are not data types supported by Java, so they are
returned as
int
values.
Unsigned bytes have values ranging from
0
to
255
. This differs
from Java's
byte
variable type, which ranges from
-128
to
127
.
Along the same line, an unsigned
short
value ranges from
0
to
65,535
, instead of the
-32,768
to
32,767
range supported by Java's
short
type.
NOTE
A data input stream's different read methods do not all return a value that can be used as
an indicator that the end of the stream has been reached.