Java Reference
In-Depth Information
Input and output can be slow, so if your program is doing anything else of importance,
try to put I/O in its own thread.
The
read()
method is declared abstract because subclasses need to change it to handle
their particular medium. For instance, a
ByteArrayInputStream
can implement this
method with pure Java code that copies the byte from its array. However, a
TelnetInputStream
needs to use a native library that understands how to read data
from the network interface on the host platform.
The following code fragment reads 10 bytes from the
InputStream
in
and stores them
in the
byte
array
input
. However, if end of stream is detected, the loop is terminated
early:
byte
[]
input
=
new
byte
[
10
];
for
(
int
i
=
0
;
i
<
input
.
length
;
i
++)
{
int
b
=
in
.
read
();
if
(
b
==
-
1
)
break
;
input
[
i
]
=
(
byte
)
b
;
}
Although
read()
only reads a byte, it returns an
int
. Thus, a cast is necessary before
storing the result in the byte array. Of course, this produces a signed byte from -128 to
127 instead of the unsigned byte from 0 to 255 returned by the
read()
method. However,
as long as you're clear about which one you're working with, this is not a major problem.
You can convert a signed byte to an unsigned byte like this:
int
i
=
b
>=
0
?
b
:
256
+
b
;
Reading a byte at a time is as inefficient as writing data one byte at a time. Consequently,
there are two overloaded
read()
methods that fill a specified array with multiple bytes
of data read from the stream
read(byte[] input)
and
read(byte[] input,
int
offset,
int length)
. The first method attempts to fill the specified array
input
. The
second attempts to fill the specified subarray of
input
, starting at
offset
and continuing
for
length
bytes.
Notice I said these methods
attempt
to fill the array, not that they necessarily succeed.
An attempt may fail in several ways. For instance, it's not unheard of that while your
program is reading data from a remote web server over DSL, a bug in a switch at a phone
company central office will disconnect you and several hundred of your neighbors from
the rest of the world. This would cause an
IOException
. More commonly, however, a
read attempt won't completely fail but won't completely succeed either. Some of the
requested bytes may be read, but not all of them. For example, you may try to read 1,024
bytes from a network connection, when only 512 have actually arrived from the server;
the rest are still in transit. They'll arrive eventually, but they aren't available at this mo‐
ment. To account for this, the multibyte read methods return the number of bytes ac‐
tually read. For example, consider this code fragment: