常用四种读取控制台输入方法:
1. Scanner读取方式
2. 字符流读取方式
3. 字节流读取方式
4. Console读取方式(JDK 1.6中新增的), 实际操作过程中, 发现不支持Eclipse自带命令行.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* @TODO 四种常用读取控制台输入方法
* @author jarg
* @creatTime: 2010-12-29 下午04:54:41
* @belongTo: com.jarg.io
* @version 1.0
*/
public class ConsoleInput
{ /* 控制台输入为字节流 */
public static InputStream in;
public static void main(String[] args)
{
try
{
ScannerInput();
CharInput();
ByteInput();
Console_Input();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 控制台输入
* */
public static void input()
{
System.out.print("\ninput data:\n > ");
in = System.in;
}
/**
* 1. Scanner读取方式
* */
public static void ScannerInput()
{
input();
Scanner s = new Scanner(in);
System.out.println("1. Scanner读取方式:\t" + s.nextLine());
}
/**
* 2. 字符流读取方式
*
* @throws IOException
* */
public static void CharInput() throws IOException
{
input();
/* InputStreamReader 是字节流通向字符流的桥梁 */
InputStreamReader ir = new InputStreamReader(in);
BufferedReader br = new BufferedReader(ir);
System.out.println("2. 字符流读取方式:\t" + br.readLine());
}
/**
* 3. 字节流读取方式
*
* @throws IOException
* */
public static void ByteInput() throws IOException
{
input();
BufferedInputStream bi = new BufferedInputStream(in);
String output = "";
int value = bi.read();
while (value != -1 && value != 10 && value != 13)
{
output = output + (char) value;
value = bi.read();
}
System.out.println("3. 字节流读取方式:\t" + output);
}
/**
* 4. Console读取方式,JDK 1.6中新增的
*
* @throws IOException
* */
public static void Console_Input() throws IOException
{
System.out.print("\ninput data:\n > ");
Console console = System.console();
if (console == null)
{
System.out.println("can not use the console.");
return;
}
System.out.println("4. Console读取方式:\t" + console.readLine());
}
}