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

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

  • 相关阅读:
    C#中跨线程访问控件问题解决方案
    asp.net网站中配置文件的加密
    C#中XML使用总结
    连接加密Access数据库的字符串设置方法
    asp.net中常用的26个优化性能的方法
    C#中Math的使用总结
    关于ASP.NET页面打印技术的总结
    域登录获取用户名字的控制
    Web界面设计基本原则
    域登录获得用户名称
  • 原文地址:https://www.cnblogs.com/zhangxiong-tianxiadiyi/p/10822154.html
Copyright © 2011-2022 走看看