This article, the second of two parts, continues to explain how to use streams with Java to interact with different storage devices. It is excerpted from chapter 15 of the book Sams Teach Yourself Java 2 in 21 days, written by Roger Cadenhead and Laura Lemay (Sams, ISBN: 0672326280).
Using Streams in Java - Console Input Streams (Page 3 of 4 )
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 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.
Listing 15.4 The Full Text of ConsoleInput.java
1: import java.io.*;
2:
3: public class ConsoleInput {
4: public static String readLine() {
5: StringBuffer response = new StringBuffer();
6: try {
7: BufferedInputStream buff = new
8: BufferedInputStream(System.in);
9: int in = 0;
10: char inChar;
11: do {
12: in = buff.read();
13: inChar = (char) in;
14: if (in != -1) {
15: response.append(inChar);
16: }
17: } while ((in != -1) & (inChar != '\n'));
18: buff.close();
19: return response.toString();
20: } catch (IOException e) {
21: System.out.println("Exception: " +
e.getMessage());
22: return null;
23: }
24: }
25:
26: public static void main(String[] arguments) {
27: System.out.print("\nWhat is your name? ");
28: String input = ConsoleInput.readLine();
29: System.out.println("\nHello, " + input);
30: }
31: }
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