转换流

转换流

一,转换流的使用

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

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

二,InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
//时处理异常的话,仍然应该使用try-catch-finally
@Test
    public void test1() throws IOException {
        FileInputStream fis = new FileInputStream("dbcp.txt");//字节流
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
        //参数2 指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存的字符集
        InputStreamReader 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);
        }
        isr.close();
    }
三,综合使用InputStreamReader和OutputStreamWriter
//时处理异常的话,仍然应该使用try-catch-finally
@Test
public void test2(){
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
        FileInputStream fis = new FileInputStream(new File("dbcp.txt"));
        FileOutputStream fos = new FileOutputStream(new File("dbcpGBK.txt"));

        isr = new InputStreamReader(fis,"UTF-8");
        osw = new OutputStreamWriter(fos,"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 @ 2022-09-21 20:48  不落微笑  阅读(38)  评论(0)    收藏  举报