IO 流—文件拷贝—FileReader + FileWriter

文件拷贝2

代码:

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

/**
 * 使用 FileReader + FileWriter 拷贝文件(只能是普通文本文件)
 * 能用记事本打开的文件都是普通文本文件
 * 普通文本文件不一定都是.txt结尾的,普通文本文件与后缀格式无关,.java文件可以拷贝
 *
 */
public class Copy02 {
    public static void main(String[] args) {

        FileReader fr = null;
        FileWriter fw = null;

        try {
            // 创建文件字符输入流
            fr = new FileReader("C:\\Users\\yao\\Desktop\\Something\\bert命令.txt");
            // 创建文件字符输出流
            fw = new FileWriter("D:/bert命令.txt");

            int readCount = 0;
            char[] chars = new char[1024 * 512]; // 一次读 1MB (Java 中 char 类型占 2 个 Byte)

            while ((readCount = fr.read(chars)) != -1){
//                fr.read(chars,0, readCount);      这行不应该加
                fw.write(chars,0, readCount);
            }
            fw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行结果:

在D盘根目录下可以找到拷贝进来的bert命令.txt文件

posted @ 2020-04-11 21:48  Jadyao  阅读(142)  评论(0)    收藏  举报