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

  • 相关阅读:
    本周总结
    本周总结:用户故事和用户场景
    排球比赛规则说明书
    我与计算机
    官网地址备份
    连续自然数序列,求取中位数方案
    Spark 实现自定义对象sequenceFile方式存储,读写示例(scala编写)
    hbase 异常
    python_初步
    redis_入门网址
  • 原文地址:https://www.cnblogs.com/quanjunkang/p/10655454.html
Copyright © 2011-2022 走看看