Monday, July 20, 2009

Java Tutorial Reading from Standard Input

Java Tutorial Reading from Standard Input

Instead of getting user input from the command-line, most users prefer inputting data when prompted by the program while it is already in execution. One way of doing this is with the use of streams. A stream is an abstraction of a file or a device that allows a series of items to be read or written. Streams are connected to physical devices such as keyboards, consoles and files. There are two general kinds of streams, byte streams and character streams. Byte streams are for binary data while character streams are for Unicode characters. System.in and System.out are two examples of predefined byte streams in java. The first one by default refers to the keyboard and the latter refers to the console.

To read characters from the keyboard, you can use the System.in byte stream warped in a BufferedReader object. The following line shows how to do this:

BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

The read method of the BufferedReader object is then used to read from the input device.

ch = (int) br.read(); //read method returns an integer

Try out this sample code.

import java.io.*;
class FavoriteCharacter {
public static void main(String args[]) throws IOException {
System.out.println("Hi, what's your favorite
character?");
char favChar;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
favChar = (char) br.read();
System.out.println(favChar + " is a good choice!");
}
}

Running this code with the character a as input generates the following output:

Hi, what's your favorite character?
a
a is a good choice!

If you prefer reading an entire line instead of reading one character at a time, you can use the readLine method.

str = br.readLine();

Here is a program almost similar to the preceding example but reads an entire string instead of just one character.

import java.io.*;

class GreetUser {
public static void main(String args[]) throws IOException {
System.out.println("Hi, what's your name?");
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
name = br.readLine();
System.out.println("Nice to meet you, " + name + "! :)");
}
}

Here is the expected output of GreetUser when the user inputs rebecca:

Hi, what's your name?
rebecca
Nice to meet you, rebecca! :)

When using streams, don't forget to import the java.io package as shown below:

import java.io.*;

One more reminder, reading from streams may cause checked exceptions to occur. Don't forget to handle these exceptions using try-catch statements or by indicating the exception in the throws clause of the method.

Java Tutorial Reading from Standard Input
Java Tutorial Reading from Standard Input
Java Tutorial Reading from Standard Input
Java Tutorial Reading from Standard Input
Java Tutorial Reading from Standard Input