我有一个目录,我在其中接收与模式 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/