Shell game: Read user input directly from the command line in Java (June 24, 1999)

The JavaWorld experts answer your most pressing Java questions -- every week

Q: Does Java have a facility like C's scanf or C++'s cin? I want to read user input straight from the command line, rather than writing any GUI code.

A: Yes, a Java application can easily read from and write to the shell that invokes it (or, in the case of a Mac, a special shell can be created for this purpose). Just as C and C++ provide standard I/O facilities like scanf/printf and cin/cout respectively, so too Java has a standard mechanism. This is accessible through the java.lang.System class via the public static field called in, which is of the type java.io.InputStream. If you need to grab the whole line from the keyboard -- if the user is just typing in a single value, like a username, for instance -- then simply use a java.io.Reader, such as java.io.BufferedReader.

Here's how to set it up:

InputStreamReader isr = new InputStreamReader ( System.in );
BufferedReader br = new BufferedReader ( isr );
String s = null;
try {
   while ( (s = br.readLine ()) != null ) {
      // do something
   }
}
catch ( IOException ioe ) {
   // won't happen too often from the keyboard
}

If you will need to do some parsing of a line of input, Java provides a powerful and general facility through the java.io.StreamTokenizer.

Here's how you set that up:

InputStreamReader isr = new InputStreamReader ( System.in );
StreamTokenizer st = new StreamTokenizer ( isr );
/* Once you have a StreamTokenizer, you can customize it's behavior.
For this example we just show basic usage.
*/
int c;
try {
   while ( true ) {
      switch ( c = st.nextToken () ) {
         case StreamTokenizer.TT_NUMBER:
            System.out.println ( "Read a number: " + st.nval );
            break;
         case StreamTokenizer.TT_WORD:
            System.out.println ( "Read a word: " + st.sval );
            break;
         case default:
            // do something in other cases (EOL, EOF,
 whitespace, quotes...)
            break;
      }
   }
catch ( IOException ioe ) {
   // Won't happen very often from the keyboard
}

This will allow you to pick off numbers and words. If you have a set of name/value pairs to parse, you could test for the names and then assign the values. If you want to enforce a specific sequence of input data, simply use the techniques above but control the sequence of tokens you expect (don't use a loop) and reject bad data as needed.

Of course, these techniques work in concert with any GUI that the Java application may have now or later on.

Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.
Related: