Java Reference
In-Depth Information
strings. For exchanging UTF-8 text with all other software, you should use an
Input
StreamReader
with the appropriate encoding. (There wouldn't be any confusion if Sun
had just called this method and its partner
writeString()
and
readString()
rather
than
writeUTF()
and
readUTF()
.)
Along with these methods for writing binary numbers and strings,
DataOutput
Stream
of course has the usual
write()
,
flush()
, and
close()
methods any
Output
Stream
class has.
DataInputStream
is the complementary class to
DataOutputStream
. Every format that
DataOutputStream
writes,
DataInputStream
can read. In addition,
DataInputStream
has the usual
read()
,
available()
,
skip()
, and
close()
methods, as well as methods
for reading complete arrays of bytes and lines of text.
There are 9 methods to read binary data that match the 11 methods in
DataOutput
Stream
(there's no exact complement for
writeBytes()
or
writeChars()
; these are
handled by reading the bytes and chars one at a time):
public
final
boolean
readBoolean
()
throws
IOException
public
final
byte
readByte
()
throws
IOException
public
final
char
readChar
()
throws
IOException
public
final
short
readShort
()
throws
IOException
public
final
int
readInt
()
throws
IOException
public
final
long
readLong
()
throws
IOException
public
final
float
readFloat
()
throws
IOException
public
final
double
readDouble
()
throws
IOException
public
final
String
readUTF
()
throws
IOException
In addition,
DataInputStream
provides two methods to read unsigned bytes and un‐
signed shorts and return the equivalent
int
. Java doesn't have either of these data types,
but you may encounter them when reading binary data written by a C program:
public
final
int
readUnsignedByte
()
throws
IOException
public
final
int
readUnsignedShort
()
throws
IOException
DataInputStream
has the usual two multibyte
read()
methods that read data into an
array or subarray and return the number of bytes read. It also has two
readFully()
methods that repeatedly read data from the underlying input stream into an array until
the requested number of bytes have been read. If enough data cannot be read, then an
IOException
is thrown. These methods are especially useful when you know in advance
exactly how many bytes you have to read. This might be the case when you've read the
Content-length
field out of an HTTP header and thus know how many bytes of data
there are:
public
final
int
read
(
byte
[]
input
)
throws
IOException
public
final
int
read
(
byte
[]
input
,
int
offset
,
int
length
)
throws
IOException
public
final
void
readFully
(
byte
[]
input
)
throws
IOException