开门见山 解决问题
这里提到的read()方法是指java.io包下InputStream里的read()。InputStream类提供了一个抽象read方法及它的两个重载方法,分别是:
abstract int read() //从键盘缓冲区读取一个字节,返回该字节的ASCII码
int read(byte[] b) //从键盘缓冲区读取一个字节数组,返回字节数
int read(byte[] b,int off,int len) // 从键盘缓冲区读取宇哥字节数组,off为偏移量,len为可读入的最大字节数,返回实际读入的字节数
-
先看第一个read():
public test () throws IOException { len=System.in.read(); System.out.print(len+" "); len=System.in.read(); System.out.print(len+" "); len=System.in.read(); System.out.println(len); }
控制台输入:123 结果显示1,2,3对应的ASCII码值:
但当控制台只输入回车,结果是:
原因是回车也会被读取,也就是回车代表的“\r”和“\n”也会被读取,而“\r”和“\n”对应的ASCII码值为13和10。
另外,用强转可以直接得到输入的数据:
public test () throws IOException {
char a = (char)System.in.read();
System.out.println(a);
}
-
再来第二个read():
public test () throws IOException { byte[] b = new byte[256]; InputStream in = System.in; int a = in.read(b); //也可以这样调用 System.out.println(a); }
控制台输入:123 结果显示1,2,3 加上“\r”和“\n”后的字节数:
-
第三个read():
其实查看int read(byte[] b)的源码可以看到,该方法会调用第三个read方法
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
接着看int read(byte b[], int off, int len)的源码,而该方法内又会调用无参的read方法:
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException(); //空指针异常
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException(); //数组下标越界异常
} else if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte)c;//第一个读入的字节在b中的偏移量
int i = 1;
try {
for (; i < len ; i++) {
c = read(); //调用无参read方法
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
} catch (IOException ee) {
}
return i;
}