Java Reference
In-Depth Information
The following sections discuss the various types of streams in more detail.
Byte streams
Byte streams represent sequences of data that's represented at its most basic, raw format, meaning
bytes (eight bits). They form the lowest level of I/O in Java so that all other streams are built on
them.
All byte streams subclass
InputStream
and
OutputStream
(inheritance, subclasses, superclasses,
and interfaces were explained in the previous chapter) and always at least provide the following
methods. For
InputStream
:
➤
int read()
: Reads the next byte of data from the input stream. Returns -1 if the end of the
stream is reached.
➤
int read(byte[] b)
: Reads some number of bytes from the input stream and stores them
into the array
b
. Returns the total number of bytes read into the buffer or -1 if there is no
more data because the end of the stream has been reached.
➤
int read(byte[] b, int off, int len)
: Reads up to
len
bytes of data from the input
stream at offset
off
into an array
b
. Returns the total number of bytes read into the buffer or
-1 if there is no more data because the end of the stream has been reached.
➤
long skip(long n)
: Skips over and discards
n
bytes of data from this input stream. Returns
the actual number of bytes skipped.
➤
void close()
: Closes this input stream and releases any system resources associated with it.
➤
int available()
: Returns an estimate of the number of bytes that can be read (or skipped
over) from this input stream without blocking.
➤
boolean markSupported()
: Tests if this input stream supports the
mark
and
reset
methods.
➤
void mark(int readlimit)
: Marks the current position in this input stream.
➤
void reset()
: Repositions this stream to the position at the time the
mark
method was last
called on this input stream.
inteGers as Bytes
You might be surprised by the fact that the
read
methods in the previous list return
int
s and not
byte
is which is also a primitive data type and would be a logical sound-
ing choice for a stream-reading and -writing byte. The reason for this is twofold.
First, the byte type in Java is signed, meaning that after conversion to a number, it
represents the range of -128 to 127, which makes calculation more cumbersome when
an unsigned number ranging between 0 and 255 is expected. Furthermore, note that
the
read
methods return -1 when the end of a stream is reached, which would then
not be able to fall inside the range of an 8-bit range (0 to 255).
continues
Search WWH ::
Custom Search