|
Reading input from console in Java
|
|
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. 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. Last published February 17, 2007
|
|