如何根据java中的日期从文件夹中获取文件

时间:2016-08-24 05:46:45

标签: java

我在具有命名约定的文件夹中有多个文件

Name_MoreName_DDMMYYYY_SomeNumber_HHMMSS.txt

如何获取具有最早日期和时间的文件(即最早的DDMMYYYY和HHMMSS)。

对于以下示例:

Name_MoreName_22012012_SomeNumber_072334.txt
Name_MoreName_22012012_SomeNumber_072134.txt
Name_MoreName_24012012_SomeNumber_072339.txt
Name_MoreName_22012012_SomeNumber_072135.txt

...最旧的文件将是

Name_MoreName_22012012_SomeNumber_072134.txt

1 个答案:

答案 0 :(得分:0)

首先,将文件名读入List<String>

然后使用了解文件名格式的比较器对列表进行排序:

public class FileNameComparator implements Comparator<String> {

    private static Pattern pattern = Pattern.compile("^.*?_([0-9]{2})([0-9]{2})([0-9]{4})_.*?_([0-9]{2})([0-9]{2})([0-9]{2})\\.txt$");
    private static int[] groupOrder = new int[]{3, 2, 1, 4, 5, 6};

    @Override
    public int compare(String filename1, String filename2) {
        Matcher matcher1 = pattern.matcher(filename1);
        Matcher matcher2 = pattern.matcher(filename2);

        return compareMatchers(matcher1, matcher2);
    }

    private int compareMatchers(Matcher matcher1, Matcher matcher2) {
        if (matcher1.matches()) {
            if (matcher2.matches()) {

                // for each group in the correct order (year, month, date, hour, minute, second)
                for (int group : groupOrder) {
                    int result = compareValues(matcher1.group(group), matcher2.group(group));
                    if (result != 0) {
                        return result;
                    }
                }

                return 0;

            } else {
                // filename 2 is incorrect pattern
                return -1;
            }
        } else {
            // filename 1 is incorrect pattern
            return 1;
        }
    }

    private int compareValues(String value1, String value2) {
        return new Integer(value1).compareTo(new Integer(value2));
    }
}

要排序:

List<String> filenames = ...; /* populate the list of filenames */
Collections.sort(filenames, new FileNameComparator());

要获得最老的,请选择第一个。要获得最年轻的,请选择最后一个。

修改:如果更新的文件名模式为:

if-logFile_2016_Jun_02_115011.txt

...然后正则表达式和代码将需要更改以能够提取参数并执行正确的比较。正则表达式将是:

^.*?_([0-9]{4})_(.{3})_([0-9]{2})_([0-9]{2})([0-9]{2})([0-9]{2})\\.txt$

...您将按顺序(1,2,3,4,5,6)处理它们,当您处理第二组时,您需要按月份名称顺序进行比较。