java将一个文件或者目录复制到另一个文件下

java将一个文件或者目录复制到另一个文件下

列如:把 F:\cc下的所有文件复制到 F:\home下面;
如果是文件的话那就是 F:\JSON\JSON.jpg 和 F:\JSON\JSON.jpg

import java.io.*;
import java.nio.file.Files;

/**
 * 进行文件或者文件夹复制到指定目录
 * @author LM
 * @date 2021-11-30 - 11:08
 */
public class FileCopyUtil {
    public static void main(String[] args) throws IOException {
    	//复制文件目录测试
        String oldPath = "F:\\cc";		//需要被复制的文件夹
        String newPath = "F:\\home"; 	//复制到的指定的文件夹
        copy(oldPath.length(),oldPath,newPath);
        
        //复制文件测试
        String oldPath = "F:\\JSON\\JSON.jpg";	//需要被复制的文件
        String newPath = "F:\\home\\JSON.jpg"; 	//复制到的指定文件
        copy(oldPath.length(),oldPath,newPath);
    }

    public static void copy(int oldLength,String oldPath, String newPath) throws IOException {
        File f1 = new File(oldPath);
        File f2 = new File(newPath+oldPath.substring(oldLength));

        //如果f1为空 直接退出
        if (!f1.exists())
            return;

        if (f1.isDirectory()) {
            //目标目录不存在此文件夹就进行新建
            if (!f2.exists())
                f2.mkdirs();

            File[] f1s = f1.listFiles();
            if (f1s != null) {
                for (File file : f1s) {
                    copy(oldLength, file.getPath(), newPath);
                }
            }
        } else {
            //如果是文件的话就进行复制
            f2.delete();    //如果存在存量数据就先删除
            Files.copy(f1.toPath(), f2.toPath());
        }
    }
}

版权声明:本文为qq_45950024原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。