关于字符流读取二进制文件

方法test1用于往“test.a”文件写入整数

@Test
public void test1() {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream("test.a");
        fos.write(7870);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方法test2用于往“test.a”文件读取数据

@Test
    public void test2() {
        FileReader fr = null;
        try {
            fr = new FileReader("test.a");

            char[] data = new char[10];
            int len;
            while ((len = fr.read(data)) != -1) {
                for (int i = 0; i < len; i++) {
                    System.out.println((long) data[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {bu
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

- 结论

  1. 当写入的整数无法在字符集编码中找到对应的字符时,字符流读取会将其转换成Unicode Character ‘REPLACEMENT CHARACTER’ (U+FFFD):65533
  2. java中字符流一次到底读几个字节?由于输入的整数找不到对应的字符,故只读1个字节。
            fos.write(0xe4);
            fos.write(0xbd);
            fos.write(0xa0);

如果输入这3个字节
test2中的char[]数组只有一个元素,20320(不强转成long将输出字符“你”)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值