Java基础IO流介绍之六——什么是桥转换(转换流)

转换流(重要)

1、概述

是字节流到字符流的桥梁,在转换的过程中,可以指定编码.

2、分类——InputStreamReader/OutputStreamWriter

InputStreamReader:
     是从字节流到字符流的桥梁,父类是Reader 它读取字节,并使用指定的编码将其解码为字符.
    它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集 
OutputStreamWriter:
      是从字符流到字节流的桥梁,父类是Writer 是从字符流到字节流的桥梁,使用指定的编码将写入的字符编码为字节.
    它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

3、构造方法

方法名 说明
InputStreamReader(InputStream in) 使用默认字符编码创建InputStreamReader对象
InputStreamReader(InputStream in,String chatset) 使用指定的字符编码创建InputStreamReader对对象
OutputStreamWriter(OutputStream out) 使用默认字符编码创建OutputStreamWriter对象
OutputStreamWriter(OutputStream out,String charset) 使用指定的字符编码创建OutputStreamWriter对象
//案例:

import java.io.*;

public class Demo13 {
    public static void main(String[] args) throws Exception {
        // 字节流  ---> 可以处理的所有的文件
        // 字符流 ---> 处理文本文件 ---> 有优势

//        FileOutputStream fileOutputStream = new FileOutputStream("file/a.txt");
//
//        // 要将字节流转换为字符流  ---> 可以指定编码
//
//        //以  GBK 编码 写入一些字符
//        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"utf-8");
//
//        outputStreamWriter.write("闺中少妇不知愁");
//
//        outputStreamWriter.close();

        FileInputStream fileInputStream = new FileInputStream("file/a.txt");

        //以GBK进行读取
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String s = bufferedReader.readLine();
        System.out.println(s);

        bufferedReader.close();


    }
}

posted @ 2021-06-25 22:21  泰初  阅读(371)  评论(0编辑  收藏  举报