IO流6、IO流_转换流的使用

转换流的使用

  1. 属于字符流(处理流)

    1. InputStreamReader:将一个字节的输入流转换为字符的输入流
    2. OutputStreamWriter:将一个字符的输出流转换为字节的输出流
  2. 作用:提供字节流与字符流之间的转换

  3. 解码:字节、字节数组 ---> 字符数组、字符串

    编码:字符数组、字符串 ---> 字节、字节数组

  4. 字符集

InputStreamReader的使用

实现字节的输入流到字符的输入流

@Test
public void test1(){
    InputStreamReader isr = null;
    try {
        FileInputStream fis = new FileInputStream("dbcp.txt");
        isr = new InputStreamReader(fis);   //使用系统默认的字符集(UTF-8)
        //具体需要使用哪个字符集取决于文件 dbcp.txt 保存时所用的字符集
        isr = new InputStreamReader(fis, "UTF-8");

        char[] cbuf = new char[20];
        int len;
        while ((len = isr.read(cbuf)) != -1){
            String str = new String(cbuf, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

InputStreamReader和OutputStreamWriter的综合使用

/*
综合使用InputStreamReader和OutputStreamWriter
 */
@Test
public void test2(){
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
        isr = new InputStreamReader(new FileInputStream("dbcp.txt"), "UTF-8");
        osw = new OutputStreamWriter(new FileOutputStream("dbcp_gbk.txt"), "GBK");

        char[] cbuf = new char[20];
        int len;
        while ((len = isr.read(cbuf)) != -1){
            osw.write(cbuf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (osw != null) {
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
posted @ 2021-11-19 23:57  叁玖贰拾柒  阅读(32)  评论(0)    收藏  举报