Java Reference
In-Depth Information
The stream classes are child classes of java.io.OutputStream and
java.io.InputStream. The reader classes are child classes of java.io.Reader, and
the writer classes are child classes of java.io.Writer. These four classes are
abstract and represent the common functionality among their child classes.
The Output Streams
The OutputStream class is the parent class of all the output streams. It contains
five methods:
public void close(). Closes the output stream.
public void flush(). Flushes any buffers.
public void write(int b). Writes a single byte.
public void write(byte [] b). Writes an array of bytes.
public void write(byte [] b, int offset, int length). Writes length number
of elements in the array starting at the index specified by offset.
The methods of the java.io.OutputStream class are not very exciting. They
only write a byte or an array of bytes. Writing bytes to an output stream is
important functionality, but what if the data you are sending comprises
more complex data such as ints, doubles, booleans, Strings, and objects?
It would be a lot of work to write the code behind the scenes that parses
the bytes into their appropriate data types. Thankfully, there are many
child classes of OutputStream that will do this type of work for you.
In fact, you will probably never need to write a class that performs low-
level I/O because there is likely a class in the java.io package that already
provides what you need. The trick is learning what each class does and
how to combine them to create the perfect stream for your needs (my
main objective in this chapter).
Each child class of OutputStream implements the write() methods inherited
from OutputStream in their own unique way. For example, the FileOutput-
Stream class writes the bytes to a file, and the BufferedOutputStream writes
the bytes to a buffer. The filtered output stream classes (those that subclass Fil-
terOutputStream) contain additional write() methods for writing different
data types or objects. For example, the DataOutputStream class contains meth-
ods for writing ints, shorts, doubles, Strings, and so on.
Search WWH ::




Custom Search