//把一个文件夹下多个文件夹 根据文件夹数量
//拆分到不同压缩文件
public static void main(String[] args) {
String sourceFolder = "E:\\桌面\\zh\\2";
String destFolder = "E:\\桌面\\zh\\3";File sourceDir = new File(sourceFolder);
File[] subFolders = sourceDir.listFiles();int numFoldersPerZip = 499;
int folderCount = 0;
int zipCount = 1;try {
ZipOutputStream zos = null;
for (File subFolder : subFolders) {
if (subFolder.isDirectory()) {
if (folderCount == 0) {
String zipFileName = destFolder + "/" + zipCount + ".zip";
zos = new ZipOutputStream(new FileOutputStream(zipFileName));
zipCount++;
}addToZip(subFolder, zos);
System.out.println("第" + zipCount + "次");
folderCount++;if (folderCount == numFoldersPerZip) {
zos.close();
folderCount = 0;
}
}
}if (zos != null) {
zos.close();
}System.out.println("Folders split and zipped successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}private static void addToZip(File folder, ZipOutputStream zos) throws IOException {
File[] files = folder.listFiles();for (File file : files) {
if (file.isDirectory()) {
addToZip(file, zos);
} else {
FileInputStream fis = new FileInputStream(file);
ZipEntry entry = new ZipEntry(folder.getName() + "/" + file.getName());
zos.putNextEntry(entry);byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}zos.closeEntry();
fis.close();
}
}
}
一个文件夹下图片根据图片名创建文件夹
public static void main(String[] args) {
String sourceFolderPath = "E:\\桌面\\zh\\1"; // 源文件夹路径
String targetFolderPath = "E:\\桌面\\zh\\2"; // 目标文件夹路径File sourceFolder = new File(sourceFolderPath);
File[] images = sourceFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg") ||
name.toLowerCase().endsWith(".png"));if (images != null) {
for (int i = 0; i < images.length; i++) {
File image = images[i];
System.out.println(image.getName());
String substring = image.getName().substring(0, 9);
String subFolderPath = targetFolderPath + "/" + substring; // 创建子文件夹路径
File subFolder = new File(subFolderPath);if (!subFolder.exists()) {
subFolder.mkdirs(); // 创建子文件夹
}try {
Path targetPath = new File(subFolder, image.getName()).toPath();
Files.move(image.toPath(), targetPath); // 移动图片到子文件夹
System.out.println("Moved: " + image.getName() + " to " + subFolderPath);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
System.out.println("No images found in the source folder.");
}
}
文章评论