Reading from System.in
What is System.in ?
It is a system variable. Its data type is InputStream. From the documentation of java.io.InputStream, the simplest method to read a byte is the read() method.
To read a line from the console, a while loop can be used to repeatedly read character until the linefeed character is read.
// read a line from console input character by character
public static void main(String[] args) throws Exception
{
String s="";
byte[] buffer=new byte[1];
while (true)
{
int n=System.in.read();
char ch=0;
if (n>0) {
ch=(char) n;
s += ch;
}
if (ch=='\n') break;
}
System.out.println("Input String="+s);
}
Reading System.in character by character is not efficient. Java does provide wrapper for InputStream so that reading a line is more simple. The following program wraps System.in with a InputStreamReader, then wraps the InputStreamReader with a BufferedReader object. Since BufferedReader supports the readLine() method, it is a more high level and thus simpler implementation.
// read a line from Console using BufferedReader
public static void main(String[] args) throws Exception
{
java.io.BufferedReader br=new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String line=br.readLine();
System.out.println(line);
}
Command Line Interpreter
Let's complete the demonstration by writing a simple command interpreter. The interpreter supports only three commands :
- time
- date
- exit
/******************************************************************************
* File : ConsoleInput.java
* Author : http://java.macteki.com/
* Description :
* Console Input Demonstration (A simple command line interpreter)
* Tested with : JDK 1.6
******************************************************************************/
class ConsoleInput
{
// a simple "command interpreter"
public static void doCommand(String line)
{
if (line.equals("time"))
{
// display current time
java.util.Date date=new java.util.Date();
java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("HH:mm");
String time=f.format(date);
System.out.println(time);
}
else if (line.equals("date"))
{
// display current time
java.util.Date date=new java.util.Date();
java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyy-MM-dd");
String dateString=f.format(date);
System.out.println(dateString);
}
else if (line.equals("exit"))
{
System.exit(1); // quit the program
}
else
{
System.out.println("Unknown command !");
}
}
public static void main(String[] args) throws Exception
{
while (true)
{
java.io.BufferedReader br=new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String line=br.readLine();
doCommand(line);
}
}
}
Thanks for reading. Comments are welcome.
No comments:
Post a Comment