Java Reference
In-Depth Information
Listing 7-40. Using System.in with a BufferedReader
// EchoBufferedStdin.java
package com.jdojo.io;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class EchoBufferedStdin {
public static void main(String[] args) throws IOException {
// Get a BufferedReader from System.in object. Note the use of
// InputStreamReader, the bridge class between the byte-based and
// the character-based stream
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = "q";
while (true) {
// Prompt user to type some text
System.out.print("Please type a message (Q/q to quit) " +
"and press enter: ") ;
// Read the text
text = br.readLine();
if (text.equalsIgnoreCase("q")) {
System.out.println("You have decided to exit the program");
break;
}
else {
System.out.println("You typed: " + text);
}
}
}
}
If you want your standard input to come from a file, you will have to create an input stream object to represent
that file and set that object using the System.setIn() method as in
FileInputStream fis = new FileInputStream("stdin.txt");
System.setIn(fis); // Now System.in.read() will read from stdin.txt file
The standard error device (generally the console) is used to display any error message. Its use in your program
is the same as a standard output device. Instead of System.out for a standard output device, Java provides another
PrintStream object called System.err . You use it as follows:
System.err.println("This is an error message.");
 
Search WWH ::




Custom Search