Java Reference
In-Depth Information
you get back a Reader , which you in turn pass to the BufferedReader constructor. The usu-
al idiom for writing this in Java is to nest the constructor calls:
BufferedReader is = new
new BufferedReader ( new
new InputStreamReader ( System . in ));
You can then read lines of text from the standard input using the readLine() method. This
method takes no argument and returns a String that is made up for you by readLine() con-
taining the characters (converted to Unicode) from the next line of text in the file. If there are
no more lines of text, the constant null is returned:
public
public class
class CatStdin
CatStdin {
public
public static
static void
void main ( String [] av ) {
try
try {
BufferedReader is =
new
new BufferedReader ( new
new InputStreamReader ( System . in ));
String inputLine ;
while
while (( inputLine = is . readLine ()) != null
null ) {
System . out . println ( inputLine );
}
is . close ();
} catch
catch ( IOException e ) {
System . out . println ( "IOException: " + e );
}
}
}
Now that we've covered the InputStreamReader , and because it's something that people
have asked me several times, I'll show how to read an Integer from the standard input:
public
public class
class ReadStdinInt
ReadStdinInt {
public
public static
void main ( String [] ap ) {
String line = null
static void
null ;
int
int val = 0 ;
try
try {
BufferedReader is = new
new BufferedReader (
new InputStreamReader ( System . in ));
line = is . readLine ();
val = Integer . parseInt ( line );
System . out . println ( "I read this number: " + val );
new
Search WWH ::




Custom Search