• Java学习笔记39(转换流)


    转换流:字符流和字节流之间的桥梁

    用于处理程序的编码问题

    OutputStreamWriter类:字符转字节流

    写文本文件:

    package demo;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    
    public class Demo {
        public static void main(String[] args) throws IOException {
            writeGBK();
            writeUTF8();
        }
    
        public static void writeGBK() throws IOException {
            FileOutputStream fos = new FileOutputStream("d:\gbk.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
            osw.write("你好");// gbk的一个汉字是2个字节
            osw.close();
        }
    
        public static void writeUTF8() throws IOException {
            FileOutputStream fos = new FileOutputStream("d:\utf8.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write("你好");// utf8的一个汉字是3个字节
            osw.close();
        }
    }

    InputStreamReader类:

    字节转字符流过程:

    这里读取上面写的文本文件:

    package demo;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Demo {
        public static void main(String[] args) throws IOException {
            readGBK();
            readUTF8();
        }
    
        public static void readGBK() throws IOException {
            FileInputStream fis = new FileInputStream("d:\gbk.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            char[] ch = new char[1024];
            int len = isr.read(ch);
            System.out.println(new String(ch, 0, len));
        }
    
        public static void readUTF8() throws IOException {
            FileInputStream fis = new FileInputStream("d:\utf8.txt");
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            char[] ch = new char[1024];
            int len = isr.read(ch);
            System.out.println(new String(ch, 0, len));
        }
    }

    这里注意,如果编码集和读取问文本不一致,就会发生乱码或者输出?的问题

  • 相关阅读:
    工业互联网兴起
    互联网经济学
    广泛应用的区块链技术
    工业互联网数据传输探讨
    谈谈网站性能
    深入探讨vue响应式原理
    工业互联网虚拟数字
    对www.518shengmao.com站资源打包,采用vue Node.js
    jquery的事件命名空间详解
    巧用索引与变量
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8290553.html
Copyright © 2020-2023  润新知