Java Reference
In-Depth Information
But is that enough? No, because the read() method can throw an IOException . So you
must either declare that your program throws an IOException , as in:
public
public static
static void
void main ( String ap []) throws
throws IOException {
...
}
or you can put a try/catch block around the read() method:
int
int b = 0 ;
try
try {
b = System . in . read ();
System . out . println ( "Read this data: " + ( char
char ) b );
} catch
catch ( Exception e ) {
System . out . println ( "Caught " + e );
}
In this case, it makes sense to print the results inside the try/catch block because there's no
point in trying to print the value you read, if the read() threw an IOException . Note that I
cavalierly convert the byte to a char for printing, assuming that you've typed a valid charac-
ter in the terminal window.
Well, that certainly works and gives you the ability to read a byte at a time from the standard
input. But most applications are designed in terms of larger units, such as integers, or a line
of text. To read a value of a known type, such as int , from the standard input, you can use
the Scanner class (covered in more detail in Scanning Input with the Scanner Class ) :
// part of ReadStdinInt15.java
Scanner sc = Scanner . create ( System . in );
int
int i = sc . nextInt ( );
For reading characters of text with an input character converter so that your program will
work with multiple input encodings around the world, use a Reader class. The particular
subclass that allows you to read lines of characters is a BufferedReader . But there's a hitch.
Remember I mentioned those two categories of input classes, Stream s and Reader s? But I
also said that System.in is a Stream , and you want a Reader . How do you get from a
Stream to a Reader ? A “crossover” class called InputStreamReader is tailor-made for this
purpose. Just pass your Stream (like System.in ) to the InputStreamReader constructor and
Search WWH ::




Custom Search