Java Reference
In-Depth Information
Up to and including Java 1.3, the only way to read and write files was to use a stream . Java 1.4 introduced a
new I/O capability in the java.nio and java.nio.channels packages for reading and writing files that
contain data of the primitive Java types, including strings. This capability completely supersedes the stream
I/O capability in this context. It is much more efficient, and in many ways easier to use, so we will limit our
discussions of streams for handling files to the extent necessary to understand the new I/O capability. We will
go into the new I/O capability in detail in the next two chapters.
Two areas where you must still use the facilities provided by the stream classes are reading from the
keyboard, and writing to the command line. We will cover both of these in this chapter along with some
general aspects of the stream classes and the relationships between them. The new I/O capability does
not provide for objects to be written and read, so you still need to use streams for this. We will look into
how we read and write objects to a file in Chapter 11 Serializing Objects .
Understanding Streams
A stream is an abstract representation of an input or output device that is a source of, or destination for,
data. You can write data to a stream and read data from a stream. You can visualize a stream as a
sequence of bytes that flows into or out of your program.
When you write data to a stream, the stream is called an output stream . The output stream can go to any
device to which a sequence of bytes can be transferred, such as a file on a hard disk, or a phone line
connecting your system to a remote system. An output stream can also go to your display screen, but only at
the expense of limiting it to a fraction of its true capability. This is output to the command line. When you
write to your display screen using a stream, it can only display characters, not graphical output. Graphical
output requires more specialized support that we will discuss from Chapter 15 onwards. Note that while a
printer can be considered notionally as a stream, printing in Java does not work this way. A printer in Java is
treated as a graphical device, so sending output to the printer is very similar to displaying graphical output on
your display screen. You will learn how printing works in Java in Chapter 20.
Search WWH ::




Custom Search