四种常用读取控制台输入方法

常用四种读取控制台输入方法:

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());
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值