我有一个目录,我在其中接收与模式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
是今天的日期。它不仅应该依赖文件名中的日期,而且还应该依赖于今天的文件系统created
或modified
时间。
这是我解决这个问题的方法。首先,我创建了两个帮助器函数,一个从文件名中检索结束日期,另一个则检索文件系统modified
时间。我认为没有必要检查created
时间,因为始终创建的时间小于或等于修改后的日期时间。
检索文件名的结束日期的函数:
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"));
}
接着,该函数检索文件的文件系统modified
日期。为此,我依靠java.nio.file.attribute.BasicFileAttributes
来检索java.nio.file.attribute.BasicFileAttributes
日期:
modified
最后,只是使用这些函数并执行验证:
private Instant getLastModifiedDate(File file) {
try {
BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
return fileAttributes.lastModifiedTime().toInstant();
} catch (IOException e) {
throw new RuntimeException("Could not read file attributes: " + file.getAbsolutePath());
}
}
因此,如果目录中的输入文件是:
private boolean isTodaysFile(File file) {
LocalDate fileNameEndDate = getEndDate(file);
// first check - validate that the file name's end date is today
if (!fileNameEndDate.isEqual(LocalDate.now())) {
return false;
}
// truncate the hours, minutes, seconds from instant since we need to validate only the day
Instant lastModifiedDate = getLastModifiedDate(file).truncatedTo(ChronoUnit.DAYS);
Instant now = Instant.now().truncatedTo(ChronoUnit.DAYS);
// second check - validate that the modified that is today
// no need to check the creation date, since creation date is always less than last modified date
return lastModifiedDate.equals(now);
}
调用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
时的输出文件是:
findLatestFile
注意: