zoukankan      html  css  js  c++  java
  • IO流之转换流

    背景:有了字符输入输出流,读取的准确率和写入的效率确实提高不少,但是尴尬的是字符输出流只能针对系统默认的编码格式,那怎么把字符串用其他格式写入文件呢

    InputStreamReader 继承于Reader,是字节流通向字符流的桥梁,可以把字节流按照指定编码 解码 成字符流

    public static void main(String[] args) throws IOException {
            File file=new File("D:\111\b.txt"); //这个b.txt文件是我手动创建的
            //读取
            //管道
            FileInputStream in=new FileInputStream(file);
            InputStreamReader reader=new InputStreamReader(in, "UTF-8");
            char[] cbuf=new char[2];
            int len;
            StringBuilder sb=new StringBuilder();
            while ((len=reader.read(cbuf))!=-1) {
                sb.append(cbuf,0,len);            
            }
            System.out.println(sb.toString());
            in.close();
        }

    读取结果:

    原因:win平台默认的utf8编码的文本性文件带有BOM,java转换流写入的utf8文件不带BOM。所以用java读取手动创建的utf8文件会出现一点乱码(?你好中国,?bom导致的)

    OutputStreamWriter 继承于Writer,是字符流通向字节流的桥梁,可以把字符流按照指定的编码 编码 成字节流

    public static void main(String[] args) throws IOException {
            //写入
            File file=new File("D:\111\a.txt");
            String str="hello中国";
            //管道
            FileOutputStream  out=new FileOutputStream(file);
            OutputStreamWriter writer=new OutputStreamWriter(out, "utf8");
            writer.write(str);
            writer.flush();
            out.close();
            writer.close();
        }

    总结:用什么类型的字符集编码,就必须用同类型的字符集解码!!

  • 相关阅读:
    就是要让你彻底学会 @Bean 注解
    Redis持久化深入理解
    设计模式内容聚合
    多线程高并发内容聚合
    实战分析:事务的隔离级别和传播属性
    28个Java开发常用规范技巧总结
    面试官:你了解过Redis对象底层实现吗
    几个高逼格 Linux 命令!
    Spring核心(IoC) 入门解读
    Python Beautiful Soup模块的安装
  • 原文地址:https://www.cnblogs.com/zhangxiong-tianxiadiyi/p/10822154.html
Copyright © 2011-2022 走看看