This program’s output depends on the two arguments specified when it was run. If you use 4 and 13, the following output is shown:
Writing:
4 5 6 7 8 9 10 11 12 13
4 5 6 7 8 9 10 11 12 13
This application consists of two classes: BufferDemo and a helper class called ArgStream. BufferDemo gets the two arguments’ values, if they are provided, and uses them in the ArgStream() constructor. The writeStream() method of ArgStream is called in line 14 to write the series of bytes to a buffered output stream, and the readStream() method is called in line 16 to read those bytes back. 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.
· The file stream is used to create a buffered input or output stream.
· The buffered stream’s write() method is used to send data, or the read() method is used to receive data.
· The buffered stream is closed.
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.
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 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 statement 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 editor and save the file as ConsoleInput.java.
The ConsoleInput class includes a main() method that demonstrates how it can be used. When you compile and run it as an application, the output should resemble the following:
What is your name? Amerigo Vespucci Hello, Amerigo Vespucci
ConsoleInput reads user input through a buffered input stream using the stream’s read() method, which returns -1 when the end of input has been reached. This occurs when the user presses the Enter key, a carriage return (character ‘\r’), or a newline (character ‘\n’).