IO流(6)—转换流

1.处理流之二:转换流

  • InputStreamReader和OutputStreamWriter

2.当作用的文件就是一个文本文件且使用字节流传输时,需要把它转换成字符流,再在外面加上缓冲流以加速传输,比如:从键盘输入System.in默认是字节流,此时就可以考虑把字节流转换成字符流,效率更高。

3.转换流提供了在字节流和字符流之间转换

4.当字节流中都是字符时转换成字符流操作更高效

  • 编码:字符串——>字符数组
  • 解码:字符数组——>字符串

    注:解码和编码时要使用同种编码方式,当文件中含有中文、英文时使用utf-8,全部为中国文时使用GBK,否则会有局部乱码

5.代码实例

public class InputOutputStreamReaderWriter {
    //将hello.txt文件,先解码成字符串,再编码成文本文件
    @Test
    public void testInputOutputStreamReaderWriter(){
        //4.定义缓冲流对象,
        BufferedReader br = null;
        //4.定义缓冲流对象,
        BufferedWriter bw = null;
        try {
            //解码
            //1.定义文件对象
            File file1 = new File("file/hello.txt");
            //2.定义字节流对象
            FileInputStream fis = new FileInputStream(file1);
            //3.定义转换流对象
            InputStreamReader isr = new InputStreamReader(fis,"utf-8");
            br = new BufferedReader(isr);
            //编码
            //1.定义文件对象
            File file2 = new File("file/hello3.txt");
            //2.定义字节流对象
            FileOutputStream fos = new FileOutputStream(file2);
            //3.定义转换流对象
            OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
            bw = new BufferedWriter(osw);
            //5.开始转化
            String str;
            while((str = br.readLine()) != null){
                bw.write("--"+str);
                bw.newLine();
                bw.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
原文地址:https://www.cnblogs.com/tengpengfei/p/10454003.html