You are on page 1of 11

Streams

Java

Stream
A stream is a communication channel that a program has with the outside world. It is
used to transfer data items in succession.
An Input/Output (I/O) Stream represents an input source or an output destination. A
stream can represent many different kinds of sources and destinations, including disk
files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects. Some streams simply pass on data; others
manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to
programs that use them: A stream is a sequential and contiguous one-way flow of data .

Byte-Based I/O & Byte Streams


Byte
streams
perform input and
output
of
8-bit
bytes. They read
and write data one
byte at a time.
Using byte streams
is the lowest level
of I/0, so if you are
reading or writing
character data the
best approach is to
use
character
streams.
Other
stream types are

Reading from InputStream


The abstract superclass InputStream declares an abstract method read() to read
one data-byte from the input source:
public abstract int read() throws IOException
The read() method:
returns the input byte read as an int in the range of 0 to 255, or
returns -1 if "end of stream" condition is detected, or
throws an IOException if it encounters an I/O error.
The read() method returns an int instead of a byte, because it uses -1 to indicate
end-of-stream.
The read() method blocks until a byte is available, an I/O error occurs, or the "endof-stream" is detected. The term "block" means that the method (and the program)
will be suspended. The program will resume only when the method returns.
Two variations of read() methods are implemented in the InputStream for reading a
block of bytes into a byte-array. It returns the number of bytes read, or -1 if "end-ofstream" encounters.

Layered (or Chained) I/O Streams


To chain the streams together, simply pass an instance of one stream into the
constructor of another stream

Character-Based I/O & Character


Streams

You might also like