Java Reference
In-Depth Information
Class
Description
InputStream
The base class for byte stream input operations.
OutputStream
The base class for byte stream output operations.
InputStream
, and
OutputStream
are both
abstract
classes. As you are well aware by now, you cannot
create instances of an abstract class - these classes only serve as a base from which to derive classes with
more concrete input or output capabilities. However, both of the classes declare methods that define a basic
set of operations for the streams they represent, so the fundamental characteristics of how a stream is accessed
are set by these classes. Generally, the
InputStream
and
OutputStream
classes, and their subclasses,
represent byte streams and provide the means of reading and writing binary data.
Basic Input Stream Operations
As we saw in the previous section, the
InputStream
class is abstract, so you cannot create objects of
this class type. Nonetheless, input stream objects are often accessible via a reference of this type, so the
methods identified in this class are what you get. The
InputStream
class includes three methods for
reading data from a stream:
Method
Description
read()
This method is abstract in the
InputStream
class, so it has
to be defined in a subclass. The method returns the next byte
available from the stream as type
int
. If the end of the
stream is reached, the method will return the value
-1
. An
exception of type
IOException
will be thrown if an I/O
error occurs.
read(byte[]
array)
This method reads bytes from the stream into successive
elements of
array
. The maximum of
array.length
bytes
will be read. The method will not return until the input data
is read, or the end of the stream is detected. The method
returns the number of bytes read, or
-1
if no bytes were read
because the end of the stream was reached. If an I/O error
occurs, an exception of type
IOException
will be thrown.
If the argument to the method is
null
then a
NullPointerException
will be thrown. An input/output
method that does not return until the operation is completed
is referred to as a
blocking
method, and you say that the
methods
blocks
until the operation is complete.
read(byte[]
array,
int
offset,
int
length)
This works in essentially the same way as the previous
method, except that up to
length
bytes are read into
array
starting with the element
array[offset]
.