获取带有日期和尾随计数器的文件名

Get filename with date and trailing counter

我需要将文件名构造为 name_<date>_N,其中 N 是相似文件数量的计数器。

String fileName = "name";
String fileNameWithDate = fileName + "_"+ new SimpleDateFormat("MMM_dd_yyyy").format(cal.getTime());

如果我尝试在给定日期下载更多次,则计数应递增 1;例如,name_Dec_10_2015_N。如何获取带有日期并递增 1 的文件名?

正如@MadProgrammer 已经写的,您需要按照以下步骤进行操作

  • 获取与您的模式匹配的所有文件的列表
  • 找到计数器最高的文件
  • 为增加的计数器创建了文件名

这是一个简短的片段,您可以将其用作起点(边缘情况的处理,例如:未找到文件等,是您自己工作的一部分,有意省略)

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, "");
        if (counterString.isEmpty()) {
            return 0;
        }
        return Integer.parseInt(counterString);
    }
}