Android 文件按日期合并压缩:高效整理文件方法
以下是一个示例代码,用于将同一文件夹下的文件按照不同的日期合并压缩。假设文件夹路径为'/path/to/files/',文件的命名格式为'YYYY-MM-DD_filename'。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileCompressor {
public static void main(String[] args) {
String folderPath = "/path/to/files/";
File folder = new File(folderPath);
// 获取文件夹下的所有文件
File[] files = folder.listFiles();
if (files == null) {
System.out.println("文件夹为空");
return;
}
// 创建日期格式化对象
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 创建压缩文件的输出流
ZipOutputStream zipOut = null;
// 遍历文件列表
for (File file : files) {
if (file.isFile()) {
// 获取文件的日期
String fileName = file.getName();
String[] parts = fileName.split("_");
if (parts.length < 2) {
System.out.println("文件名格式不正确:" + fileName);
continue;
}
String dateString = parts[0];
try {
// 解析日期
Date date = dateFormat.parse(dateString);
String targetFolder = dateFormat.format(date);
// 创建目标文件夹
File targetFolderFile = new File(folderPath + targetFolder);
if (!targetFolderFile.exists()) {
targetFolderFile.mkdir();
}
// 创建压缩文件
File zipFile = new File(folderPath + targetFolder + ".zip");
if (!zipFile.exists()) {
zipFile.createNewFile();
}
// 创建压缩文件的输出流
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
// 将文件添加到压缩文件中
addToZipFile(file, zipOut);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭压缩文件的输出流
if (zipOut != null) {
try {
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private static void addToZipFile(File file, ZipOutputStream zipOut) throws IOException {
FileInputStream fileIn = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOut.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileIn.read(buffer)) != -1) {
zipOut.write(buffer, 0, bytesRead);
}
fileIn.close();
}
}
这段代码会将同一文件夹下的文件按照日期创建对应的文件夹,并将该日期下的所有文件压缩到一个以日期命名的压缩文件中。请确保在运行代码之前将'/path/to/files/'替换为正确的文件夹路径。
原文地址: https://www.cveoy.top/t/topic/fpnc 著作权归作者所有。请勿转载和采集!