字符流和字节流

java字符流和字节流

字符流和字节流的区别

字节流字符流
使用缓存
是否编码
读取字节数中文1个,英文1个中文2个,英文1个

是否使用缓存

字节流不使用缓存,字符流使用缓存
字节流:

public static void main(String[] args) throws IOException {
        File f = new File("d:" + File.separator + "test.txt");
        OutputStream  out = new FileOutputStream(f);
        String str = "Hello World!!!";
        out.write(str.getBytes());
        out.flush();//在此处断住查看文件,文件写入Hello World!!!
        out.close();
    }

字符流:

public static void main(String[] args) throws IOException {
        File f = new File("d:" + File.separator + "test.txt");
        Writer out = new FileWriter(f);
        String str = "Hello World!!!";
        out.write(str);
        out.flush();//在此处断住查看文件,文件并没有写入Hello World!!!
        out.close();
    }

是否编码

字节流读入和写出都是使用byte类型或者int类型所以自然就不存在编码问题
字符流牵扯读入之后需要将字节转换为字符,而字符的显示本身就需要编码,具体参见aip接口

读取字节数

字节流1个,取值范围在0~255之间

public static void main(String[] args) throws IOException {
        File f = new File("d:" + File.separator + "test.txt");
        InputStream  reader = new FileInputStream(f);
        System.out.println(reader.read());
        reader.close();
    }

读中文“我是程序员”

输出:
230
字节流读取中文是一个字节

读英文“abcdef”

输出:97
字节流读取英文是一个字节

字符流2个,取值范围在0~65536之间

public static void main(String[] args) throws IOException {
        File f = new File("d:" + File.separator + "test.txt");
        Reader reader = new FileReader(f);
        System.out.println(reader.read());
        reader.close();
    }

读中文“我是程序员”

输出:
37812
字符流读取中文是一个字节

读英文“abcdef”

输出:97
字符流读取英文是一个字节

使用场景(后续补充,暂未想好)

字符流:
建议在需要缓存的情况下使用,比如文件拷贝,数据的即时传输
字节流:
建议在读取字节的情况下使用比如读取中文,在需要缓存的情况下使用,比如socket通信

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值