其他分享
首页 > 其他分享> > IO(Transition)-转换流

IO(Transition)-转换流

作者:互联网

IO的转换流

1- 转换流的理解:

1-转换流
将"字节流"和"字符流"相互转化
用处:读取的是utf-8 ==> 输出变成gbk

2- InputStreamReader、OutputStreamWriter的理解
InputStreamReader --> 将"字节流"转换为"字符流"。是"字节流"通向"字符流"的桥梁
OutputStreamWriter -->将"字符流"转换为"字节流"。(这里注意是将"字符流")是"字符流"通向"字节流"的桥梁

2- 转换流的使用

(我的案例:读取"UTF-8"文件 ---> 放回出"GBK文件"类型)
 //本来为了安全,应该要写try-catch,为了代码简洁,略了
    public void test() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("/Users/ccc/Desktop/testIO/hello.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/ccc/Desktop/testIO/hello-Translation.txt");

        //包一个"转化流"
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "gbk");

        //读写
        char[] cbuf = new char[1024];
        int len;
        while ((len = inputStreamReader.read(cbuf)) != -1) {
            outputStreamWriter.write(cbuf);
        }
        inputStreamReader.close();
        outputStreamWriter.close();


    }

标签:字符,转换,字节,Transition,IO,new,InputStreamReader,OutputStreamWriter
来源: https://www.cnblogs.com/chen-zhou1027/p/16375861.html