【问题标题】:Get filename with date and trailing counter获取带有日期和尾随计数器的文件名
【发布时间】:2015-05-31 09:56:45
【问题描述】:

我需要将文件名框定为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 的文件名?

【问题讨论】:

  • File#existsFile#listFiles(FileFilter) 将在这里为您提供帮助...
  • 我不明白。可以举个例子吗?
  • 您将要尝试列出与您使用的前缀匹配的所有文件。当有多个时,您将需要找出有多少并增加数字...
  • 如果有任何代码示例会有所帮助
  • 你的意思是this previous example

标签: java filenames


【解决方案1】:

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

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

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

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);
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多