转换流

概述

JDK中提供了两个类将字节流转换为字符流,分别是InputStreamReader和OutputStreamWriter。其中InputStreamReader是Reader的子类,OutputStreamWriter是Writer的子类。

字节输入流转换为字符输入流

    public static void main(String[] args){
        FileInputStream fis = null;
        InputStreamReader isr = null;
        try {
            fis = new FileInputStream("3.txt");

            //参数1:要转换的字节输入流,参数2:指定编码名称
            isr = new InputStreamReader(fis);

            char[] chars = new char[10];
            while (true){
                int len = isr.read(chars);
                if (len == -1){
                    break;
                }
                System.out.println(new String(chars,0,len));
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (fis != null)
                    fis.close();

                if(isr != null)
                    isr.close();

            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

运行结果如下:

天青色等烟雨而我

字节输出流转换为字符输出流

    public static void main(String[] args) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream("4.txt");

            //参数1:要转换的字节输入流,参数2:指定编码名称
            osw = new OutputStreamWriter(fos);
            osw.write("炊烟袅袅升起,而我在等你");

            //注意转换的字符输出流在关闭之前应该先刷新
            osw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();

                if (osw != null)
                    osw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

运行结果展示如下:

需要注意的是,在上述代码中,转换字符输出流需要先刷新管道再关闭,否则会报出流已关闭异常

posted on 2021-10-19 12:08  技术小伙伴  阅读(100)  评论(0)    收藏  举报