编程语言
首页 > 编程语言> > Java中的转换流

Java中的转换流

作者:互联网

文章目录

转换流

一、概念

提供字节流与字符流之间的转换。

二、分类

三、示例

(一)InputStreamReader

@Test
    public void test() {
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
            fileInputStream = new FileInputStream("hello.txt");
            //将字节转为字符,可以设置字符编码
            inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");

            char[] cbuf = new char[10];
            int len;
            while ((len = inputStreamReader.read(cbuf)) != -1) {
                for (int i = 0; i < len; i++) {
                    System.out.print(cbuf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

(二)综合

@Test
    public void test2() {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        InputStreamReader inputStreamReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            //1、创建文件对象
            File hello = new File("hello.txt");
            File hi = new File("hi.txt");

            //2、创建输入输出流对象
            fileInputStream = new FileInputStream(hello);
            fileOutputStream = new FileOutputStream(hi);

            //3、创建转换流
            inputStreamReader = new InputStreamReader(fileInputStream);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");//以gbk的方式写入字节

            //4、读取、写入
            char[] cbuffer = new char[20];
            int len;
            while ((len = inputStreamReader.read(cbuffer)) != -1) {
                outputStreamWriter.write(cbuffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5、关闭流
            if(outputStreamWriter !=  null){
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStreamReader != null){
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

标签:转换,InputStreamReader,printStackTrace,Java,new,fileInputStream,null,inputStreamRe
来源: https://blog.csdn.net/weixin_46245201/article/details/121363114