用 Java 把一个文件夹下的文件随机分为 x 份 x = 总份数 / n
以下内容由 chatGPT,一次生成而来,强大且高效,直接跑过,记录下,下次直接用
用Java实现文件夹内文件的随机分组是一个很好的主意,因为Java提供了更强大的文件处理能力和错误处理机制。下面是一个Java程序示例,它实现了将指定文件夹内的文件随机分成若干组的功能:
import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class FileDistributor {public static void main(String[] args) {if (args.length != 2) {System.out.println("Usage: java FileDistributor <folder_path> <n>");System.exit(1);}String folderPath = args[0];int n = Integer.parseInt(args[1]);File folder = new File(folderPath);if (!folder.isDirectory()) {System.out.println("The specified path is not a directory.");System.exit(1);}File[] files = folder.listFiles();if (files == null || files.length == 0) {System.out.println("No files found in the directory.");System.exit(1);}List<File> fileList = Stream.of(files).collect(Collectors.toList());Collections.shuffle(fileList);for (int i = 0; i < fileList.size(); i += n) {File newFolder = new File(folderPath + "/group_" + (i / n + 1));if (!newFolder.exists()) {newFolder.mkdir();}for (int j = i; j < i + n && j < fileList.size(); j++) {File file = fileList.get(j);file.renameTo(new File(newFolder.getPath() + "/" + file.getName()));}}System.out.println("Files distributed into " + ((fileList.size() - 1) / n + 1) + " groups.");}}
这个Java程序首先检查输入参数的合法性,然后列出指定文件夹内的所有文件。它将这些文件随机排序,然后按照指定的每组数量n分组。对于每组文件,程序将创建一个新的子文件夹,并将文件移动到这些子文件夹中
要运行此程序,请将代码保存为FileDistributor.java,并使用Java编译器编译它
javac FileDistributor.java
然后运行编译后的程序,如下所示:
java FileDistributor /path/to/your/folder
这会将/path/to/your/folder中的文件随机分成每组5个文件的多个子文件夹。请确保你有权限访问和修改指定的文件夹
转载请注明作者和出处,并添加本页链接。
原文链接: //xiaochun.zrlog.com/split-folder.html