关于System.in(系统输入)的一点研究

java程序中加入下面这段代码,神奇的事情就发生了:

	Scanner sc = new Scanner(System.in);
		try{
			System.out.println("名字: ");
			String str = sc.next();
			System.out.println("用户输入" + str);
		}catch(Exception e){
			e.printStackTrace();
		}

 我们就可以从键盘输入一段字符串被系统接收了。

出于好奇,看了下源代码,发现最为关键的地方是它调用了System.in里面的read方法。

System.in
in
public static final InputStream in“标准”输入流。此流已打开并准备提供输入数据。通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。 
 

模拟了下实现过程:

	private static char[] lineBuffer;
	/**
	 * read
	 * @throws IOException
	 */
	public static void read() throws IOException {
		InputStream in = System.in;
		char[] buf = lineBuffer;
		if (buf == null) {
			buf = lineBuffer = new char[128];
		}
		int room = buf.length;
		int offset = 0;
		int c;

		 while (true) {
			 c = in.read();


			if (--room < 0) {
					buf = new char[offset + 128];
					room = buf.length - offset - 1;
					System.arraycopy(lineBuffer, 0, buf, 0, offset);
					lineBuffer = buf;
			}
			buf[offset++] = (char) c;
		}
		//return String.copyValueOf(buf, 0, offset);
	}
	
	public static String readLine() throws IOException {

		InputStream in = System.in;
		char[] buf = lineBuffer;
		if (buf == null) {
			buf = lineBuffer = new char[128];
		}
		int room = buf.length;
		int offset = 0;
		int c;

		loop: while (true) {
			switch (c = in.read()) {


			case -1:
			case '\n':
				break loop;

			case '\r':
				int c2 = in.read();
				if ((c2 != '\n') && (c2 != -1)) {
					if (!(in instanceof PushbackInputStream)) {
						in = new PushbackInputStream(in);
					}
					((PushbackInputStream) in).unread(c2);
				}
				break loop;

			default:
				if (--room < 0) {
					buf = new char[offset + 128];
					room = buf.length - offset - 1;
					System.arraycopy(lineBuffer, 0, buf, 0, offset);
					lineBuffer = buf;
				}
				buf[offset++] = (char) c;
				break;
			}
		}
		if ((c == -1) && (offset == 0)) {
			return null;
		}
		return String.copyValueOf(buf, 0, offset);
	}
 

调用我写的read方法,可以一直不停的输入。

调用readLine()方法,当有换行的时候,就停止了。

当然,java.io.BufferedReader的构造器也可以传入一个System.in

 

		BufferedReader bReader = null;
		try{
			System.out.println("名字: ");
			bReader = new BufferedReader(new InputStreamReader(System.in));
			String str  = bReader.readLine();
			System.out.println("用户输入" + str);
		}catch(Exception e){
			e.printStackTrace();
		}

 我们也可以从键盘进行输入,然后读取一下,效果和Scanner是一样 的。

现在在看这段代码,倍感亲切了!

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值