ptg7068951
290 HOUR 20: Reading and Writing Files
The Consoleclass includes a main()method that demonstrates how it can be
used. When you run the application, the output should resemble Figure 20.2.
FIGURE 20.2
Running the Consoleapplication.
The Consoleclass contains one class method, readLine(), which receives
characters from the console. When the Enter key is hit, readLine()returns
a Stringobject that contains all the characters that are received.
If you save the Consoleclass in a folder that is listed in your CLASSPATH
environment variable (on Windows), you can call Console.readLine()
from any Java program that you write.
Writing Data to a Stream
In the java.iopackage, the classes for working with streams come in
matched sets. There are FileInputStreamand FileOutputStreamsclasses
for working with byte streams, FileReaderand FileWriterclasses for
working with character streams, and many other sets for working with
other kinds of stream data.
To begin writing data, you first create a Fileobject that is associated with
an output stream. This file doesn’t have to exist on your system.
You can create a FileOutputStreamin two ways. If you want to append
bytes onto an existing file, call the FileOutputStream()constructor
method with two arguments: a Fileobject representing the file and the
booleanof true. The bytes you write to the stream are tacked onto the end
of the file.
If you want to write bytes into a new file, call the FileOutputStream()
constructor method with a Fileobject as its only object.
After you have an output stream, you can call different write()methods
to write bytes to it:
. Call write()with a byte as its only argument to write that byte to
the stream.
NOTE
TheConsoleclass is also the
world’s least satisfying text
adventure game. You can’t
enter the building,wade in the
stream,or even wander off. For
a more full-featured version of
this game,which is called
Adventure,visit the Interactive
Fiction archive at
http://www.wurb.com/if/game/1.