设计两个方法,分别实现拷贝一个文本文件(分别用字节流和字符流实现)

import java.io.*;

/**
 * @Description 设计两个方法,分别实现拷贝一个文本文件(分别用字节流和字符流实现)
 */
public class FileCopy {

    public static void main(String[] args) {
    	//这里用的相对路径
        fileCopy("file\\source", "file\\source");
        fileCopy2("file\\src", "file\\src");
    }

    /**
     * 使用字节流实现文件的拷贝
     * @param srcPath 原文件路径
     * @param dstPath 目标文件路径
     * @return 拷贝是否成功
     */
    private static boolean fileCopy(String srcPath, String dstPath) {
        // 1. 判断目标路径下是否有存在的文件、目录
        if (checkExists(dstPath)) {
            return false;
        }
        // 2. 文件的拷贝
        try (InputStream inputStream = new FileInputStream(srcPath);
             OutputStream outputStream = new FileOutputStream(dstPath)) {
            // 3. 实例化一个字节数组
            byte[] array = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(array)) != -1) {
                // 4. 将读取到的数组,写入到输出流中
                outputStream.write(array, 0, length);
            }
            outputStream.flush();
            return true;
        }
        catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 使用字符流实现文件的拷贝
     * @param srcPath 原文件路径
     * @param dstPath 目标文件路径
     * @return 拷贝的结果
     */
    private static boolean fileCopy2(String srcPath, String dstPath) {
        // 1. 判断目标文件是否存在
        if (checkExists(dstPath)) {
            return false;
        }
        // 2. 循环读取目标文件中的数据
        try (Reader reader = new FileReader(srcPath); Writer writer = new FileWriter(dstPath)) {
            // 3. 循环读取源文件中的数据
            char[] array = new char[100];
            int length = 0;
            while ((length = reader.read(array)) != -1) {
                // 4. 将读取到的数据写入到输出流
                writer.write(array, 0, length);
            }
            writer.flush();
            return true;
        }
        catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean checkExists(String path) {
        return new File(path).exists();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值