JAVA基础复习-输入、输出转换流整合(实现文本文件复制)

1、因为转换流也属于处理流,所以效率比节点流高很多;

2、转换流解决了字节流读取文本文件时可能出现的中文乱码问题,有了转换流,就可以处理.doc文档了,不管.doc文件是否有图片或文字,都可以使用转换流进行读取、写出。

package com.winson.iotest;

import org.junit.Test;

import java.io.*;

/**
 * @description:输入、输出转换流整合(复制文件)
 * @date: 2020/7/5 22:43
 * @author: winson
 */
public class InputSteamReaderOutputStreamWriterTest {

    @Test
    public void test1() {
        InputStreamReader inputStreamReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            FileInputStream fileInputStream = new FileInputStream("hello.txt");
            FileOutputStream fileOutputStream = new FileOutputStream("hello_GBK.txt");
            inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
            outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK");
            char[] chars = new char[20];
            int len;
            while ((len = inputStreamReader.read(chars)) != -1) {
                outputStreamWriter.write(chars, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStreamWriter != null) {
                    outputStreamWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

posted @ 2020-07-05 22:53  温森  阅读(228)  评论(0编辑  收藏  举报