从接收输入值说起
在日常的开发应用中,有时候需要直接接收外部设备如键盘等的输入值,而对于这种数据的接收方式,我们一般有三种方法:字节流读取,字符流读取,Scanner 工具类读取。
字节流读取
直接看一个例子:
public class Demo01SystemIn {
public static void main(String[] args) throws IOException {
int a = System.in.read();
System.out.println(a);
char c = 'a';
System.out.println((int) c);
}
}
运行程序之后,会被 read 方法阻塞,这时候在控制台输入一个字符 a,那么上面的程序两句话都会输出 97,这个没问题,因为小写字母 a 对应的就是 97,那么假如我们输入一个中文会出现什么结果呢?
把上面示例中的 a 修改为 中,然后运行程序,在控制台同样输入 中,则会得到 228 和 20013,这就说明我们控制台输入的 中 并没有全部读取,原因就是 read 只能读取 1 个字节,为了进一步验证结论,我们将上面的例子进行改写:
public class Demo01SystemIn {
public static void main(String[] args) throws IOException {
char a = (char) System.in.read();//读取一个字节
System.out.println(a);
char c = '中';
System.out.println(c);
}
}
运行之后得到如下结果:
可以看到,第一个输出乱码了,因为 System.in.read() 一次只能读取一个字节,而中文在 utf-8 编码下占用了 3 个字节。正因为 read 方法一次只能读取一个字节,所以其范围只能在 -1~255 之间,-1 表示已经读取到了结尾。
那么如果想要完整的读取中文应该怎么办呢?
字符流读取
我们先看下面一个例子:
public class Demo01SystemIn {
public static void main(String[] args) throws IOException {
InputStreamReader inputStreamReader1 = new InputStreamReader(System.in);
int b = inputStreamReader1.read();//只能读一个字符
System.out.println(b);
InputStreamReader inputStreamReader2 = new InputStreamReader(System.in);
char[] chars = new char[2];
int c = inputStreamReader2.read(chars);//读入到指定char数组,返回当前读取到的字符数
System.out.println