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是一样 的。
现在在看这段代码,倍感亲切了!