Java 按日期分组文件

Java 按日期分组文件,java,Java,我想根据文件被修改的月份和年份来压缩文件。我能够使用简单的日期格式获得月份和年份 package codes; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.text.SimpleDateFormat; public class UsingLoops { private static final String FOLDER_PATH = "C:\\Use

我想根据文件被修改的月份和年份来压缩文件。我能够使用简单的日期格式获得月份和年份

package codes;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class UsingLoops 
{
private static final String FOLDER_PATH = "C:\\Users\\Desktop\\Zip";

public static void main(String[] args) throws IOException 
{
    File dir = new File(FOLDER_PATH);

    File[] files = dir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File directory, String fileName)
        {
            if (fileName.endsWith(".txt"))
            {
                return true;
            }
            return false;
        }
        });

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    for(File f:files)
    {
        System.out.println(f.getName());

        String month = sdf.format(f.lastModified());

        int j = Integer.parseInt(month);

        System.out.println(j);
    }
  }
}
现在我想按月份和年份列出这些文件。 比如说

201412
201411等

以及如何自动将邮政编码命名为年和月

帮帮我


我知道如何使用java压缩,但我需要它根据时间和命名自动化,希望你明白我的意思,你可以使用
SortedMap
,由
java.util.Date
键入,来建立一个
列表,其中包含针对特定月份/年份修改的文件,例如

File[] files = ...;

Map<Date, List<File>> mapFiles = new TreeMap<>();

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
for (File file : files) {
    try {
        // This might seem weird, but basically, this will trim
        // off the date (day) and time, making it possible to
        // better match elements which fall within the same month
        // and year...
        // You could use a Calendar here to extract the Year and Month 
        // values, it would mean you're not creating so many short lived
        // objects, but that's up to you
        Date date = sdf.parse(sdf.format(new Date(file.lastModified())));
        List<File> group = mapFiles.get(date);
        if (group == null) {
            group = new ArrayList<>(25);
            mapFiles.put(date, group);
        }
        group.add(file);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
}

// Now, you can process the groups individually...
for (Date date : mapFiles.keySet()) {
    System.out.println(sdf.format(date));
    for (File file : mapFiles.get(date)) {
        System.out.println("    " + file);
    }
}

您可以使用
String
作为键,但如果您想控制排序顺序,则
Date
Integer
会更好

我知道如何压缩文件,但我需要一个按时间排列的列表,和自动命名您可以使用
数组。排序
,并使用自定义的
比较器
按您想要的顺序对
文件
进行排序。您可以使用
SimpleDateFormat
根据您的要求对值进行格式设置,首先需要将其转换为
Date
不仅是开始,我还需要每个月定义的每个列表。“按时间列出清单”是什么意思?“自动命名”呢?如果你的问题不是关于压缩文件,为什么会出现在你的标题中?你的问题呢?“这不仅仅是开始,我每个月都需要每个列表”-对不起,这是什么意思?谢谢,它现在正在工作,但是如何自动命名你的意思是什么?什么文件名?如果您指的是zip文件,为什么不直接使用
filezipfile=newfile(sdf.fomat(date)+“.zip”)?非常感谢您的帮助
Map<Date, Map<Date, List<File>> mapFiles = ...