zoukankan      html  css  js  c++  java
  • 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));
        }
    }

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

  • 相关阅读:
    基于jQuery解决ios10以上版本缩放问题
    移动端h5模拟长按事件
    一篇讲SpringBoot+kafka很好的文章
    Liquibase+SpringBoot的简单使用笔记!update+rollback
    集合异同,找出新增元素和删除元素
    spring-security-结合JWT的简单demo
    IDEA SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统
    提取swagger内容到csv表格,excel可打开
    spring mvc 黑马 笔记
    手机页面图片显示高低不一致
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8290553.html
Copyright © 2011-2022 走看看