Java Reference
In-Depth Information
NOTE
Additional techniques for input and output programming are
offered in the
java.nio
package. Because this package is most
useful in network programming, it is discussed on Day 17,
“Communicating Across the Internet.”
In Java, all data is written and read using streams. Streams, like the bodies of water that
share the same name, carry something from one place to another.
A
stream
is a path traveled by data in a program. An
input stream
sends data from a
source into a program, and an
output stream
sends data from a program to a destination.
You will deal with two types of streams today: byte streams and character streams.
Byte
streams
carry integers with values that range from
0
to
255
. A diverse assortment of data
can be expressed in byte format, including numerical data, executable programs, Internet
communications, and bytecode—the class files run by a Java virtual machine.
In fact, every kind of data imaginable can be expressed using either individual bytes or a
series of bytes combined with each other.
Character streams
are a specialized type of byte stream that handles only textual data.
They're distinguished from byte streams because Java's character set supports Unicode, a
standard that includes many more characters than could be expressed easily using bytes.
Any kind of data that involves text should use character streams, including text files, web
pages, and other common types of text.
Using a Stream
The procedure for using either a byte stream or a character stream in Java is largely the
same. Before you start working with the specifics of the
java.io
classes, it's useful to
walk through the process of creating and using streams.
For an input stream, the first step is to create an object associated with the data source.
For example, if the source is a file on your hard drive, a
FileInputStream
object could
be associated with this file.
After you have a stream object, you can read information from that stream by using one
of the object's methods.
FileInputStream
includes a
read()
method that returns a byte
read from the file.