Homepage
 
Search
ERICSSON GLOBAL
Reading input from console in Java 
*
 
Membership
Membership
Get knowledge, support and experience in our free developer program.
Log in
User name
Password

Friday, July 9, 2004

All content and software implementations are not Ericsson-supported products. Note that Ericsson does not represent nor hold responsibility for the content from this area.

At the dawn of the Java era (versions 1.0 and 1.1) it was hard to read input from a standard console. Developers wanted something like the STDIO library in C. Fortunately, a new approach using Java Readers and Writers for character-based input from the IO package instead of the traditional Streams is here to save the day and reduce development times.

There is no obvious System.in.readLine() in the InputStream API. The closest thing available is the readLine method in the BufferedReader class. So, how can we “convert” an InputStream to a BufferedReader. One problem is that BufferedReader has no constructor or method that accepts an InputStream. The InputStreamReader class serves as an adapter between the worlds of bytes and characters.

There’s an equivalent class for the OutputStream and the Writer, but there are no equivalent classes that adapt from characters to bytes. This absence is intentional; it means that we shouldn’t be trying to convert from characters to bytes, because the encodings are not platform independent, although it is fine to convert from bytes to characters.
Bearing all this in mind, let's take a look at a small echo example.

import java.io.*;

 

public class Echo {

    public static void main(String args[]) throws Exception{

        // This is where the magic happens.  We have a plain old InputStream

        // and we want to read lines of text from the console.

        // To read lines of text we need a BufferedReader but the BufferedReader

        // only takes Readers as parameters.

        // InputStreamReader adapts the API of Streams to the API of Readers;

        // receives a Stream and creates a Reader, perfect for our purposes.

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

        String input = "";

        while(true){

            System.out.print("ECHO< ");

            //As easy as that. Just readline, and receive a string with

            //the LF/CR stripped away.

            input = in.readLine();

            //Is a faster alternative to: if (input == null || input.equals(""))

            //The implementation of equals method inside String checks for

            // nulls before making any reference to the object.

            // Also the operator instance of returns false if the left-hand operand is null

            if ("".equals(input)){

                break;

            }else 

          // Here you place your command pattern code.

            if ("ok".equals(input)){

                System.out.println("OK command received: do something …");

            }

            //Output in uppercase

            System.out.println("ECHO> " + input.toUpperCase());

        }

        //We exit without closing the Reader, since is standard input, 

// you shouldn't try to do it.

        // For all other streams remember to close before exit.

    }

}

This example code is tested and useable – just copy and paste. Use the ability to read from the console to create interactive tests and examples. This capacity allows you to test your code more thoroughly, resulting in shorter development times.

One last recommendation before you start coding: the method readLine from the class DataInputStream was used for the purpose of reading text lines from a file or console. This method is now less valued because it doesn’t handle properly the different encoding schemes available in modern-day programming, such as UTF-8 or UTF-16.

In a nutshell, for text you should always use Readers and Writers. Use Streams for binary I/O.

Avelino Benavides



E-mail this page icon Tell your friends    Send this page    Send this page    Send this page   Send this page   Send this page Printable version icon Printable version

Last published February 17, 2007
The latest poll
Opinion column
Personal thoughts and analysis on business and technology.