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

    1   OutputStreamWriter类

    OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的字符编码表,将要写入流中的字符编码成字节。它的作用的就是,将字符串按照指定的编码表转成字节,在使用字节流将这些字节写出去。

    public class Demo04 {
        public static void main(String[] args) throws IOException {
            //明确目的地
            FileOutputStream fos=new FileOutputStream("D:\test\c.txt",true);
            //给字符流添加指定码表的功能
            OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
            osw.write("你好吗");
            //关闭资源
            osw.close();
        }
    }

    2     InputStreamReader类

    InputStreamReader 是字节流通向字符流的桥梁:它使用指定的字符编码表读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。

    public class Demo05 {
        public static void main(String[] args) throws IOException {
            //明确数据源
            FileInputStream fis=new FileInputStream("D:\test\c.txt");
            //添加转换流
            InputStreamReader isr=new InputStreamReader(fis,"utf-8");
            int len=0;
            while((len=isr.read())!=-1){
                System.out.println((char)len);
            }
            isr.close();
        }
    }

    3  总结

    字符转换流原理:字节流+编码表。

    字节--->字符 : 看不懂的--->看的懂的。  需要读。输入流。 InputStreamReader

    字符--->字节 : 看的懂的--->看不懂的。  需要写。输出流。 OutputStreamWriter

  • 相关阅读:
    622 CircularQueue C#
    x盒子
    Cygwin、MinG、MSys区别与联系(转)
    Spring集成MyBatis完整示例
    mybatis学习 (五) POJO的映射文件
    mybatis学习(四)——config全局配置文件解析
    json字段为null时输出空字符串
    mybatis学习(一)不使用 XML 构建 SqlSessionFactory
    数据库 ----jdbc连接池的弊端
    Spring @Import注解 —— 导入资源
  • 原文地址:https://www.cnblogs.com/quanjunkang/p/10655454.html
Copyright © 2011-2022 走看看