Java根据文件名中的日期查找目录中的最新文件

标签 java spring file file-io nio

我有一个目录,我在其中接收与模式 ABC_STOCK_List_YYYYMMDD_YYYYMMDD.csv 匹配的文件。 我正在用 java 编写一个计划服务,我需要检查文件是否为今天的日期,然后对该文件执行我的处理。

ABC_STOCK_List_20200220_20200220.csv
ABC_STOCK_List_20200219_20200219.csv
ABC_STOCK_List_20200218_20200218.csv
ABC_STOCK_List_20200217_20200217.csv

到目前为止我有这个:

private Optional<File> findLatestFile(final String dir) {
    return Stream.of(new File(dir).listFiles())
                 .filter(
                         file -> !file.isDirectory()
                                 && file.getName().startsWith(prefix)
                                 && file.getName().endsWith(".csv")
                                 && isTodaysFile(file)
                 )
                 .findFirst();

}

private boolean isTodaysFile(File file) {
    return false;
}

我需要有关 isTodaysFile() 的帮助,应检查后者的 YYYYMMDD 是否是今天的日期。它不仅应该依赖于文件名中的日期,还应该依赖于文件系统创建修改时间(也应该是今天)。

最佳答案

这是我解决这个问题的方法。首先,我创建了两个辅助函数,一个用于从文件名中检索结束日期,另一个用于检索文件系统修改时间。我认为没有必要检查创建时间,因为创建时间总是小于或等于修改日期时间。

检索文件名结束日期的函数:

private LocalDate getEndDate(File file) {
    String fileName = file.getName();
    String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf("."));
    String[] fileNameChunks = fileNameWithoutExtension.split("_");
    String endDateAsString = fileNameChunks[fileNameChunks.length - 1];

    return LocalDate.parse(endDateAsString, DateTimeFormatter.ofPattern("yyyyMMdd"));
}

接下来,该函数检索文件的文件系统修改日期。为此,我使用 Files#getLastModifiedTime检索修改日期:

private LocalDate getLastModifiedDate(File file, ZoneId zoneId) {
    try {
        return ZonedDateTime
                .ofInstant(Files.getLastModifiedTime(file.toPath()).toInstant(), zoneId)
                .toLocalDate();
    } catch (IOException e) {
        throw new RuntimeException("Could not read file attributes: " + file.getAbsolutePath());
    }
}

最后,它只是调用这些函数并执行验证:

boolean isTodaysFile(File file) {
    Clock systemUTCClock = Clock.systemUTC();
    LocalDate localDateNow = LocalDate.now(systemUTCClock);

    LocalDate fileEndDate = getEndDate(file);

    // first check - validate that the file name's end date is today
    if (!fileEndDate.isEqual(localDateNow)) {
        return false;
    }

    LocalDate lastModifiedDate = getLastModifiedDate(file, systemUTCClock.getZone());

    // second check - validate that the modified that is today
    // no need to check the creation date, since creation date is always less or equal to the last modified date
    return lastModifiedDate.equals(localDateNow);
}

我正在使用 Clock.systemUTC() 并基于此实例化所有日期,以确保我们始终使用 UTC

  • LocalDate.now(systemUTCClock)
  • systemUTCClock.getZone()

如果目录中的输入文件是:

ABC_STOCK_List_20200220_20200220.csv
ABC_STOCK_List_20200219_20200219.csv
ABC_STOCK_List_20200218_20200218.csv
ABC_STOCK_List_20200217_20200217.csv
ABC_STOCK_List_20200305_20200305.csv

在撰写本文时,当前日期是2020 年 5 月 3 日。调用 findLatestFile 时的输出文件为:

ABC_STOCK_List_20200217_20200305.csv

注释:

  • 我没有对文件名格式执行任何验证。如果格式有问题,您在检索结束日期时可能会遇到一些错误。

关于Java根据文件名中的日期查找目录中的最新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60546191/

相关文章:

java - Spring 集成测试环境不调度 JPA 实体生命周期事件

java - 如何在并发环境中注意网络请求?

c - 尝试使用 fread 读取字节但出现 Segmentation Fault 11

c# - 如果目录内容在迭代过程中发生变化,Directory.EnumerateFiles 会发生什么?

java - 如何从sql数据库检索数据以及该数据应显示在jtable中

java - 如何在Elasticsearch中获取嵌套类型

java - 为什么我的内部类确实看到非静态变量?

java - android如何在保存记录之前检查java中的字符串值是否已存在于mysql数据库中

java - 通过嵌套列表对象中的多个值查找对象 Hibernate、Jpa

c FILE 程序错误 : double free or corruption