工作小记

IO流小练习-JAVA 复制文件,复制文件夹

2020-05-29  本文已影响0人  叫子非鱼啊

练习要求:

实现效果

查看文件数量是否相同

思路

package iotest;

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

public class TestCopy {
    public static void main(String[] args) {
        String srcPath = "D:\\Program Files\\7-Zip";
        String destPath = "D:\\temp\\t\\";
//      copyFile(srcPath,destPath);
        copyFolder(srcPath,destPath);
    }
    
    
    private static void copyFolder(String srcPath, String destPath) {
        File srcFile = new File(srcPath);
        File[] files = srcFile.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                File destFile = new File(destPath+file.getPath().split(":")[1]);
                copyFile(file.getAbsolutePath(), destFile.getParent()+File.separator);
            }else {
                copyFolder(file.getAbsolutePath(), destPath);
            }
        }
    }

    /**
     * 复制文件
     * @param srcPath
     * @param destPath
     */
    private static void copyFile(String srcPath,String destPath) {
        File srcFile = new File(srcPath);
        File destFile = new File(destPath+srcFile.getName());
        
        // 文件夹不存在时创建文件夹
        if (!destFile.getParentFile().exists()) {
            boolean result = destFile.getParentFile().mkdirs();
            if (result) {
                System.out.println(destFile.getParentFile()+"创建成功");
            }else {
                System.out.println(destFile.getParentFile()+"创建失败");
            }
        }
        try(
            BufferedReader br = new BufferedReader(new FileReader(srcFile));
            PrintWriter pw = new PrintWriter(new FileWriter(destFile));
        ){
            String line;
            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
            System.out.println(destFile.getAbsolutePath()+"  复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

————————END————————

想看电影关注我的公众号:电影资源集(支持输入电影名称自动回复了)

喜欢我的文章,就点击关注我吧
上一篇下一篇

猜你喜欢

热点阅读