文件的复制(包括文件夹和子文件)

package 综合练习;

import java.io.*;

// 文件复制
public class CopyFile {
    public static void main(String[] args) throws IOException{
        String scr = "C:\\Users\\ly\\Desktop\\代码\\java\\src";
        String dest = "D:Test01";
        //copyFile(scr, dest);
        copyFolder(scr,dest);
    }
    // 复制文件
    public static void copyFile(String srcFile, String destFile) throws IOException{
        File src = new File(srcFile);
        File dest = new File(destFile);
        dest.getParentFile().mkdirs();
        dest.createNewFile();
        try(FileReader fr = new FileReader(src);
            BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter(dest);
            BufferedWriter bw = new BufferedWriter(fw)){
            String line = null;
            while((line = br.readLine()) != null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void copyFolder(String srcFile, String destFile)throws IOException{
        File src = new File(srcFile);
        File dest = new File(destFile);  // C:\Users\ly\Desktop\代码\java\src\Test01.java\数据流---错误
        dest.getParentFile().mkdirs(); // 创建文件夹
        File[] files = src.listFiles();
        String dirName = "";  // dirName 存储文件夹名称
        String tmpdestFile = dest.getPath(); // 临时文件地址
        String tmpsrcFile = src.getPath();
        for (File f:files) {
            if(f.isDirectory()){
                dirName = "\\" + f.getName();  // 文件夹名字
                tmpsrcFile += dirName; // 需要添加的文件夹加 原始路径
                tmpdestFile += dirName;
                copyFolder(tmpsrcFile, tmpdestFile); // 递归------一直递归到是文件为止

                tmpdestFile = destFile; // 重新初始文件地址,如果不初始的话会写入错误地址
                tmpsrcFile = srcFile;
            }
            if(f.isFile()){
                // D:Test01\Test01.java\数据流
                destFile += "\\" + f.getName();
                copyFile(f.getPath(), destFile);
                destFile = tmpdestFile; // 初始文件上一个路径 -- 不初始化会出错比如:  // D:Test01\Test.java\Test.java
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值