JAVA基础复习-FileRead与FileWriter结合使用示例:字符输入、输出流整合(实现文本类文件的复制)

package com.winson.iotest;

import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @description:字符输入、输出流整合(实现文件的复制)
 * @date: 2020/7/5 19:21
 * @author: winson
 */
public class FileReadFileWriterTest {

    @Test
    public void test1() {

        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            File file = new File("hello.txt");
            File file1 = new File("hello_out.txt");

            fileReader = new FileReader(file);
            fileWriter = new FileWriter(file1);
            char[] chars = new char[5];
            //记录每次读入到chars数组中的字符的个数
            int len;
            while ((len = fileReader.read(chars)) != -1) {
                fileWriter.write(chars, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

posted @ 2020-07-05 19:38  温森  阅读(198)  评论(0编辑  收藏  举报