获取带日期和尾随计数器的文件名 [英] Get filename with date and trailing counter
问题描述
我需要将文件名框架为 name_< date> _N
,其中N是类似文件数量的计数器。
I need to frame a file name as name_<date>_N
, where N is a counter for the number of similar files.
String fileName = "name";
String fileNameWithDate = fileName + "_"+ new SimpleDateFormat("MMM_dd_yyyy").format(cal.getTime());
如果我尝试在给定日期下载更多次,则计数应增加1;例如, name_Dec_10_2015_N
。如何获取带日期的文件名并增加1?
If I try to download more times for a given date, the count should be incremented by 1; for example, name_Dec_10_2015_N
. How do I get filename with date and incremented by 1?
推荐答案
正如@MadProgrammer已编写的那样,您需要按照以下步骤进行操作
As @MadProgrammer already wrote you need to do it in following steps
- 获取与您的模式匹配的所有文件的列表
- 查找具有最高计数器的文件
- 为增加的计数器创建了文件名
这是一个简短的片段,您可以将其用作一个起点(处理边缘情况,如:没有找到文件等,有意省略并且是你自己工作的一部分)
Here is short snippet which you can use as a starting point (the handling of edge cases, like: no file found, etc., are intentionally omited and part of your own work)
public class IncreaseCounter {
static final SimpleDateFormat FILE_DATE = new SimpleDateFormat("MMM_dd_yyyy");
public static void main(String[] args) {
// filter files which matches the given pattern
FilenameFilter fileNameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches("^name_..._.._.....*\\.txt");
}
};
// needed to sort the file list based on the file counter
Comparator<File> sortByCounter = new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return getFileCounter(file1.getName()) - getFileCounter(file2.getName());
}
};
String filesLocation = "resources/";
int highestCounter = 0;
// read the files matching the filter
File[] listFiles = new File(filesLocation).listFiles(fileNameFilter);
List<File> files = Arrays.asList(listFiles);
// sort the files by their file counter
Collections.sort(files, sortByCounter);
// get the highest counter
String fileWithHighestCounter = files.get(files.size() - 1).getName();
highestCounter = getFileCounter(fileWithHighestCounter);
String nextFileName = String.format("name_%s_%d.txt",
FILE_DATE.format(new Date()),
highestCounter + 1
);
System.out.println("nextFileName = " + nextFileName);
}
/**
* Extract the file counter.
* @param fileName the file name
* @return 0 - if the file has no counter, otherwise the counter value
*/
static int getFileCounter(String fileName) {
String namePatternWithCounter = "^name_..._.._...._*(.*)\\.txt";
String counterString = fileName.replaceAll(namePatternWithCounter, "$1");
if (counterString.isEmpty()) {
return 0;
}
return Integer.parseInt(counterString);
}
}
这篇关于获取带日期和尾随计数器的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!