IO流 p9 转换流-InputStreamReader 和 OutputStreamWriter

转换流-InputStreamReader 和 OutputStreamWriter

  • 介绍

    1. InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流);
    2. OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流);
    3. 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流;
    4. 可以在使用时指定编码格式(比如 utf-8,gbk,gb2312,ISO8859-1等),解决乱码问题;
  • InputStreamReader

    代码演示:

    import java.io.*;
    
    /**
     * @author: 86199
     * @date: 2023/5/7 17:18
     * @description: 演示使用 InputStreamReader 转换流解决中文乱码问题
     * 将字节流 FileInputStream 转换成字符流 InputStreamReader,指定编码 gbk/utf-8
     */
    public class InputStreamReader_ {
        public static void main(String[] args) throws IOException {
            String filePath = "e:\\a.txt";
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));
    
            //读取
            String s = bufferedReader.readLine();
            System.out.println("读取内容 = " + s);
            //关闭流
            bufferedReader.close();
        }
    }
    
    
  • OutputStreamWriter

    代码演示:

    package com.hsp.transformation;
    
    import java.io.*;
    
    /**
     * @author: 86199
     * @date: 2023/5/7 17:31
     * @description: 演示 OutputStreamWriter 使用,把FileOutputStream 字节流,转成OutputStreamWriter
     * 指定处理的编码 gbk/utf-8/utf8
     */
    public class OutputStreamWriter_ {
        public static void main(String[] args) throws IOException {
            String filePath = "e:\\test.txt";
            String charSet = "utf8";
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
    
            outputStreamWriter.write("只因你太美");
    
            outputStreamWriter.close();
    
            System.out.println("文件按照" + charSet + "保存成功");
        }
    }
    
    

热门相关:斗神战帝   特工重生:快穿全能女神   无限杀路   特工重生:快穿全能女神