Java Reference
In-Depth Information
Even though they are moving data in two directions, the
writeStream()
and
readStream()
methods are substantially the same. They take the following format:
The filename,
numbers.dat
, is used to create a file input or output stream.
n
The file stream is used to create a buffered input or output stream.
15
n
The buffered stream's
write()
method is used to send data, or the
read()
method
is used to receive data.
n
The buffered stream is closed.
n
Because file streams and buffered streams throw
IOException
objects if an error occurs,
all operations involving the streams are enclosed in a
try
-
catch
block for this exception.
TIP
The
Boolean
return values in
writeStream()
and
readStream()
indi-
cate whether the stream operation was completed successfully.
They aren't used in this program, but it's good practice to let
callers of these methods know if something goes wrong.
Console Input Streams
One of the things many experienced programmers miss
when they begin learning Java is the ability to read textual or numeric input from the
console while running an application. There is no input method comparable to the output
methods
System.out.print()
and
System.out.println()
.
Now that you can work with buffered input streams, you can put them to use receiving
console input.
The
System
class, part of the
java.lang
package, has a class variable called
in
that is an
InputStream
object. This object receives input from the keyboard through the stream.
You can work with this stream as you would any other input stream. The following state-
ment creates a new buffered input stream associated with the
System.in
input stream:
BufferedInputStream command = new BufferedInputStream(System.in);
The next project, the
ConsoleInput
class, contains a class method you can use to receive
console input in any of your Java applications. Enter the text of Listing 15.4 in your edi-
tor and save the file as
ConsoleInput.java
.