Saturday, January 10, 2009

Command Line Echo

The program in this blog answers the following questions:
  1. How to read input from the command line?
  2. How to echo data read from the command line?
  3. What wrapper must be used to read a line of input from the command line?

This simple program demonstrates the use of the java.io package to read command line data.

CommandLineReader.java

//--------Start of source code------

import java.io.*;

public class CommandLineReader
{
public static void main(String [] args)
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{
System.out.println(br.readLine());
}
catch(IOException ioex)
{
System.out.println("An IOException was thrown");
}
}
}

//--------End of source code-------

Compile this program using:
javac -cp . CommandLineReader.java

Run this program using:
java -classpath CommandLineReader

When you execute this program, you will be prompted to enter some text on the command line. Enter some text and see how it is echoed back to you on the command line itself.

Explanation:
What this program does is that it makes a new InputStreamReader that takes input from the command line(represented by System.in), because data from the command line is treated as an Input Stream. Now since my intention is to read one line at a time, i need to save each character entered by the user in a buffer. The BufferedReader class does this for me. Now when a complte line is entered(i.e. the usr presses the enter/return key), i retrieve this line from the BufferedReader and print it back on the command line.

Happy Programming ;)

Signing Off
Ryan

No comments: