【发布时间】:2020-03-01 02:03:36
【问题描述】:
我有一个包含 1000 多个文件的目录,我需要根据月份压缩它们,重命名它们并将压缩文件放在一个文件夹中。我通常手动执行此操作,但我厌倦了这样做。我编写了一个重命名文件并将它们放在新文件夹中的程序,但我不知道如何按月过滤或在 Windows 10 上使用 java 压缩它们。
String path = "C:\\\\Users\\\\srs\\\\Desktop\\\\Test\\notProcessed";
File[] filelist = new File(path).listFiles();
for (File file : filelist) {
Date d = new Date(file.lastModified());
Calendar c = Calendar.getInstance();
c.setTime(d);
int iyear = c.get(Calendar.YEAR);
int imonth = c.get(Calendar.MONTH);
String syear = Integer.toString(iyear);
String smonth = Integer.toString(imonth);
System.out.println(syear + "_" + smonth);
String destpath = "C:\\\\Users\\\\srs\\\\Desktop\\\\Test\\notProcessed\\\\TestZip\\\\";
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream(destpath + syear + "_" + smonth + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + file);
System.out.println("File Added : " + file.getAbsolutePath().toString());
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
这就是我目前所拥有的。该程序运行,但它没有给我所需的结果。它应该给我 3 个标记为(基于 lastModified())2019_07、2019_08、2019_09 的 zip 文件夹,但我得到的是 2019_06、2019_07、2019_08、2019_10,每个文件夹只有 1 个文件。
【问题讨论】:
-
请添加有关您的操作系统的信息。另外,请向我们展示您的程序代码,也许有人可以添加此功能。
-
“按月过滤”是什么意思?是否应该只包含某个月份之前的文件?还是按月对文件进行分组,每个组都放在自己的 ZIP 文件中?
cutoff对此有何影响? -
只有上个月的文件,而不是当前月份的文件,按月分组,每个组进入自己的 zip。
cutoff以前用于获取超过 2 天的文件。我不确定我是否会在尝试编写的程序中使用它。
标签: java directory zip filtering file-rename