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();
    }

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

原文地址:https://www.cnblogs.com/zhangxiong-tianxiadiyi/p/10822154.html