InputStream

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值