1. FileInputStream
byte占1个字节8位,范围:-128 ~ 127。
int占4个字节32位,范围:-2^31 ~ 2^31-1。
char占2个字节16位,范围:0~65536。
-27在内存中以补码形式存储,即:11100101。以int形式读取即为:229;强转char为乱码。
String str="好孩纸";
byte[] arr=str.getBytes();
for(byte e : arr) {
System.out.print(e + " ");//-27 -91 -67 -27 -83 -87 -25 -70 -72
}
FileInputStream in = new FileInputStream( "src\\3.txt");
int i = -1;
//i接收的是read方法读取到的码值
//中文的码值为负数,如:好孩纸:
//-27 -91 -67 -27 -83 -87 -25 -70 -72
while((i=in.read())!=-1){
//将i表示的码值,转换成字符类型
System.out.println("char:"+(char)i);//乱码
System.out.println("int:"+i);//码值 229 165 189 229 173 169 231 186 184
}
in.close();
FileInputStream in1 = new FileInputStream( "2.txt");
byte[] by = new byte[1024];
int n = 0;
while((n=in1.read(by))>0){
for(byte e : by) {
System.out.print(e + " ");//-27 -91 -67 -27 -83 -87 -25 -70 -72
}
System.out.println();
String st = new String(by,0,n);
System.out.println(st);//好孩纸
}
in1.close();
2. FileReader
FileReader reader = new FileReader(path + "3.txt");
//i保存的是读取的字符的码值
int i1 = -1;
while((i1=reader.read())!=-1){
System.out.print((char)i1);//正确打印:好孩纸
System.out.print(i1+" ");//中文:22909 23401 32440
}
reader.close();
FileReader in2 = new FileReader(path +"3.txt");
char[] c = new char[1024];
int ii = -1;
while((ii =in2.read(c))!=-1){
//将字符数组转换成字符串
System.out.println(new String(c,0,ii));//好孩纸
System.out.println(Arrays.toString(c));//[好, 孩, 纸, ,...]
}
in2.close();
3. InputStreamReader
//创建读取文件的字节流对象
InputStream in3 = new FileInputStream("1.txt");
//创建转换流对象
InputStreamReader isr = new InputStreamReader(in3,"utf-8");
//使用转换流去读字节流中的字节
int ch = 0;
while((ch = isr.read())!=-1){
System.out.println((char)ch);//好孩纸
System.out.println(ch);//22909 23401 32440
}
//关闭流
isr.close();