Java Reference
In-Depth Information
public static void main(String[] args) {
PrintStream ps = new PrintStream(new DummyStandardOutput());
// Set the dummy standard output
System.setOut(ps);
// The following messages are not going anywhere
System.out.println("Hello world!");
System.out.println("Is someone listening?");
System.out.println("No. We are all taking a nap!!!");
}
}
(No output will be printed.)
You can use the
System.in
object to read data from a standard input device (usually a keyboard). You can also
set the
System.in
object to read from any other
InputStream
object of your choice, such as a file. You can use the
read()
method of the
InputStream
class to read bytes from this stream.
System.in.read()
reads a byte at a time from
the keyboard. Note that the
read()
method of the
InputStream
class blocks until data is available for reading. When
a user enters data and presses the Enter key, the entered data becomes available, and the
read()
method returns one
byte of data at a time. The last byte read will represent a new-line character. When you read a new-line character from
the input device, you should stop further reading or the
read()
call will block until the user enters more data and
presses the Enter key again. Listing 7-39 illustrates how to read data entered using the keyboard.
Listing 7-39.
Reading from the Standard Input Device
// EchoStdin.java
package com.jdojo.io;
import java.io.IOException;
public class EchoStdin {
public static void main(String[] args) throws IOException{
// Prompt the user to type a message
System.out.print("Please type a message and press enter: ");
// Display whatever user types in
int c = '\n';
while ((c = System.in.read()) != '\n') {
System.out.print((char) c);
}
}
}
Since
System.in
is an instance of
InputStream
, you can use any concrete decorator to read data from the
keyboard; for example, you can create a
BufferedReader
object and read data from the keyboard one line at a time
as string. Listing 7-40 illustrates how to use
System.in
object with a
BufferedReader
. Note that this is the kind of
situation when you will need to use the
InputStreamReader
class to get a character-based stream (
BufferedReader
)
from a byte-based stream (
System.in
). The program keeps prompting the user to enter some text until the user enters
Q
or
q
to quit the program.