Archive for I/O

Getting input from keyboard

Posted in Programming with tags , , , on November 17, 2006 by wsjoung

import java.io.*;
InputStreamReader yetBufferedInput = new InputStreamReader(System.in);
BufferedReader bufferedInput = new BufferedReader(yetBufferedInput);
// Once you have created a BufferedReader, you can read either individual characters, or whole lines, from it.

try {
String inputLine = bufferedInput.readLine();

if ( inputLine != null ) {
// … process “inputLine” …
} else {
System.err.println( “No more keyboard input.” );
}
} catch ( IOException error ) {
System.err.println( “Error reading keyboard: ” + error );
}

try {
int input = bufferedInput.read();
if ( input >= 0 ) {
char c = (char) input;
// … process the input character in variable “c”
} else {
System.err.println( “No more keyboard input.” );
}
} catch( IOException error ) {
System.err.println(“Error reading keyboard:”+error );
}

readLine() can be used to read a line of text from BufferedReader, and read() reads a charactor.

try {
bufferedInput.close();
} catch ( IOException error ) {
System.err.println(“Couldn’t close the reader:” + error);
}

after that, you may close the connection to the stream and data source.