复制文件夹下的多个同名文件到新文件夹并随机重命名

import java.io.*;
import java.util.Random;

public class FileUtils {
    public static void main(String[] args) throws IOException {
        String source = "源文件夹";
        String dest = "目标文件夹";
        FileUtils  fu = new FileUtils(source,dest,1000);
        fu.execute();
    }

   /**源文件夹*/
    private String sourcePath ;
    /**目标文件夹*/
    private String destPath;
    /**复制的数量*/
    private int number;

    /**
     * 构造器
     * @param sourcePath 源文件夹
     * @param destPath 目标文件夹
     * @param number 复制的数量
     */
    public FileUtils(String sourcePath, String destPath ,int number){
        this.sourcePath = sourcePath;
        this.destPath = destPath;
        this.number = number;
    }

    /**
     * execute
     * 
     * @throws IOException
     */
    public void execute() throws IOException {
        File path = new File(sourcePath);
        File [] files = path.listFiles();
        for (int i = 0; i < number; i++) {
            String newName = getRandomCharAndNumr(32);
            boolean flag = true;
            for (File file : files) {
                if (flag) {
                    flag = false;
                    copyFileUsingFileStreams(
                            file,
                            new File(destPath + "\\" + newName + ".pdf")
                    );
                } else {
                    copyFileUsingFileStreams(
                            file,
                            new File(destPath + "\\" + newName + ".xml")
                    );
                }
            }
            System.out.println("已完成" + (i + 1) + "个");
        }
    }

    /**
     * 复制文件
     * @param source 源文件
     * @param dest 目标文件
     * @throws IOException
     */
    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    /**
     * 生成随机的字符(小写字母和数字组合)
     * @param length 生成字符的长度
     * @return 生成的字符
     */
    public  String getRandomCharAndNumr(Integer length) {
        String str = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            boolean b = random.nextBoolean();
            if (b) { // 字符串
                // int choice = random.nextBoolean() ? 65 : 97; 取得65大写字母还是97小写字母
                str += (char) (97 + random.nextInt(26));// 取得大写字母
            } else { // 数字
                str += String.valueOf(random.nextInt(10));
            }
        }
        return str;
    }
}

猜你喜欢

转载自blog.csdn.net/asd104/article/details/80301785