Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Streams 289

You can work with this input stream like any other. The following statement
creates a buffered input stream associated with the System.ininput stream:


BufferedInputStream bin = new BufferedInputStream(System.in);


The next project, the Consoleclass, contains a class method you can use to
receive console input in any of your Java applications. Enter the text from
Listing 20.2 in a new empty Java file named Console.


LISTING 20.2 The Full Text of Console.java
1: importjava.io.*;
2:
3: public classConsole {
4: public staticString readLine() {
5: StringBuffer response = new StringBuffer();
6: try {
7: BufferedInputStream bin = new
8: BufferedInputStream(System.in);
9: int in = 0;
10: charinChar;
11: do {
12: in = bin.read();
13: inChar = (char) in;
14: if (in != -1) {
15: response.append(inChar);
16: }
17: } while((in != -1) & (inChar != ‘\n’));
18: bin.close();
19: returnresponse.toString();
20: } catch(IOException e) {
21: System.out.println(“Exception: “+ e.getMessage());
22: return null;
23: }
24: }
25:
26: public static voidmain(String[] arguments) {
27: System.out.print(“You are standing at the end of the road “);
28: System.out.print(“before a small brick building. Around you “);
29: System.out.print(“is a forest. A small stream flows out of “);
30: System.out.println(“the building and down a gully.\n”);
31: System.out.print(“> “);
32: String input = Console.readLine();
33: System.out.println(“That’s not a verb I recognize.”);
34: }
35: }

Free download pdf