我有一个文件夹,我从其他应用程序接收文件并存储在该文件夹中。文件格式为
“ ABC_DIFL_MMDDYYYYmillisecs.log”
我不想手动传递文件名,我想根据今天的日期动态读取文件。有什么可能的方法可以做到这一点???
TIA
最佳答案
您可以使用DateFormat类获取Date对象并设置其格式,以便可以将其用作文件名的一部分。
DateFormat df = new SimpleDateFormat("MMddyyyy");
String filename = "ABC_DIFL_" + df.format(new Date()) + ".log";
您可以在the API page上阅读有关SimpleDateFormat的格式。
查找具有毫秒后缀的文件时,您还会遇到更棘手的问题。这可以从具有毫秒精度的Date对象创建,但是您怎么知道正确的毫秒呢?
您需要做的是获取目录中文件的列表并对其进行测试,以查找以今天的日期开头的文件。可以按以下步骤完成:
public File findTodaysFirstFile(File directory) {
DateFormat df = new SimpleDateFormat("MMddyyyy");
String prefix = "ABC_DIFL_" + df.format(new Date());
for (File current : directory.listFiles()) {
if (current.getName().startsWith(prefix)) {
return current;
}
}
// handle failure here, throw an exception or return null as you prefer
}