【Java文件管理】批量生成文件,按时间格式路径生成

1. 在指定文件夹底下随机生成文件夹及文件

1.1 参数

参数名含义默认值
path生成文件夹路径/home/cathay10/workSpace/log
minSum随机数生成器20
randomSum随机文件数量,最大为minSum+randomSum10
startDate指定开始日期,为空则默认1970-01-01开始2021/01/01
numberOfDates生成的日期数量9
plusDays日期偏移量,输入0为当前日期,正数为当前日期后n天,负数为当前日期前n天0
prefix文件名前缀log_
suffix文件名后缀_log
fileType文件类型_log
fileName文件名file
fileNameRandom文件名随机数长度(含数字、字母)6
charSize设置数组大小为1MB,可以根据需要调整10 * 1024 * 1024
fileSize设置文件大小为1MB,可以根据需要调整10 * 1024 * 1024
fillChar填充字符,用于填充文件大小x
生成的文件夹格式/ /home/cathay10/workSpace/log/yyyy/MM/dd/

1.2 代码

package com.api.apidemo.tool.file;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author yhc
 * @description 批量生成文件
 */
public class BatchCreateFile {
    /**
     * 文件路径
     */
    public static final String path = "/home/cathay10/workSpace/log";
    /**
     * 随机数生成器
     */
    static Random random = new Random();
    /**
     * 最小文件数量
     */
    static int minSum = 5;
    /**
     * 随机文件数量,最大为minSum+randomSum
     */
    static int randomSum = 5;
    /**
     * 生成的日期数量
     */
    static int numberOfDates = 1500;
    /**
     * 日期偏移量,输入0为当前日期,正数为当前日期后n天,负数为当前日期前n天
     */
    static int plusDays = 0;
    /**
     * 指定开始日期格式
     */
    static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    /**
     * 指定开始日期
     */
    static String startDate = "2000/01/01";
    /**
     * 文件名前缀
     */
    static String prefix = "log_";
    /**
     * 文件名后缀
     */
    static String suffix = "_log";
    /**
     * 文件名后缀
     */
    static String fileType = "txt";
    /**
     * 文件名
     */
    static String fileName = "file";
    /**
     * 文件名随机数长度(含数字、字母)
     */
    static int fileNameRandom = 6;
    /**
     * 设置数组大小为1MB,可以根据需要调整
     */
    static int charSize = 1 * 1024 * 1024;
    /**
     * 设置文件大小为1MB,可以根据需要调整
     */
    static int fileSize = 1 * 1024 * 1024;
    /**
     * 填充字符,用于填充文件大小
     */
    static char fillChar = 'x';

    public static void main(String[] args) {
        batchCreateFile();
    }

    /**
     * 批量生成文件
     */
    public static void batchCreateFile() {
        Set<LocalDate> uniqueDates = generateRandomPastDate(numberOfDates, plusDays);
        uniqueDates.forEach(date -> createFile(date, randomSum == 0 ? minSum : random.nextInt(randomSum) + minSum));
    }

    /**
     * 创建文件
     *
     * @param currentDate   当前日期
     * @param numberOfFiles 随机文件数量
     */
    private static void createFile(LocalDate currentDate, int numberOfFiles) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String formattedDate = currentDate.format(formatter);

        String outputPath = path + "/" + formattedDate;
        Path dirPath = Paths.get(outputPath);

        try {
            // 创建输出目录
            Files.createDirectories(dirPath);
            for (int i = 1; i <= numberOfFiles; i++) {
                //需要判断文件是否存在,如果存在,则重新生成文件名
                Path filePath = randomFileName(dirPath);

                // 创建文件
                try (FileWriter writer = new FileWriter(filePath.toFile())) {
                    // 1MB的字符数组
                    char[] buffer = new char[charSize];
                    StringBuilder sb = new StringBuilder(buffer.length);
                    for (int x = 0; x < buffer.length; x++) {
                        // 填充字符
                        sb.append(fillChar);
                    }
                    String content = sb.toString();
                    // 转换为字节
                    long bytesToWrite = fileSize;
                    while (bytesToWrite > 0) {
                        writer.write(content);
                        bytesToWrite -= content.getBytes().length;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成指定数量的不重复的过去日期
     *
     * @param numberOfDates 日期数量
     * @param plusDays      最大日期:输入0为当前日期,正数为当前日期后n天,负数为当前日期前n天
     */
    public static Set<LocalDate> generateRandomPastDate(int numberOfDates, int plusDays) {
        Set<LocalDate> uniqueDates = new HashSet<>();
        while (uniqueDates.size() < numberOfDates) {
            if (StringUtils.isEmpty(startDate)) {
                startDate = "1970/01/01";
            }
            // 开始日期
            LocalDate startDates = LocalDate.parse(startDate, formatter);
            // 当前日期(含今天),随机生成一个过去日期,
            LocalDate today = LocalDate.now().plusDays(plusDays);
            long randomDays = random.longs(startDates.toEpochDay(), today.toEpochDay()).findFirst().getAsLong();
            LocalDate date = LocalDate.ofEpochDay(randomDays);
            uniqueDates.add(date);
        }
        return uniqueDates;
    }

    /**
     * 生成随机字符串
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String randomString(int length) {
        String letters = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        String result = "";

        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(letters.length());
            result += letters.charAt(index);
        }
        return result;
    }

    /**
     * 生成文件名,如果文件名已存在,则重新生成
     */
    public static Path randomFileName(Path dirPath) {
        Path filePath = dirPath.resolve(prefix + fileName + randomString(fileNameRandom) + suffix + "." + fileType);
        File file = filePath.toFile();
        if (file.exists()) {
            filePath = randomFileName(dirPath);
        }
        return filePath;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值