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

时间:2015-03-27 06:19:22

标签: java filenames

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

1 个答案:

答案 0 :(得分:0)

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