Home > Software design >  How to find and retrieve full filename with changeable date suffix
How to find and retrieve full filename with changeable date suffix

Time:11-28

I have a file that is being generated every time. The name of the file changes every time and consists of a fixed prefix, followed by suffix of the current date. I need a way to find the filename using maybe regex or something else, using only the known prefix like:

 String localFile = "my_path"   "PREFIX_*";
 File localFile = new File(localFileStr);
 if (localFile.exists()) {
     return localFile;
 }

Example of the filename:

the prefix: PREFIX_
pattern1: yyyy-mm-dd
pattern2: _hh-mm-ss 
all together: PREFIX_yyyy-mm-dd_hh-mm-ss 
Actual example: PREFIX_2022-11-27_10-45-14

As you can see, it consists of the prefix, date of year, month and day separated by _ then hour, minutes and seconds. I need something to add, maybe separate for 2 dates patterns and a way to use regex on searching through the given directory.

CodePudding user response:

You can use java.time API to parse the filename into a LocalDateTime and then compare the date part with today's date. If the parsing fails or the criterion for the current date is not met, you can return false from FileFilter#accept.

Demo of parsing and the criterion for the current date:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("'PREFIX_'uuuu-MM-dd_HH-mm-ss", Locale.ENGLISH);
        String fileName = "PREFIX_2022-11-27_10-45-14";
        LocalDateTime ldt = LocalDateTime.parse(fileName, parser);
        System.out.println(ldt);
        System.out.println(ldt.toLocalDate().equals(LocalDate.now()));
    }
}

Output:

2022-11-27T10:45:14
true

Now, let's create a FileFilter using the above-explained concept:

FileFilter todaysFilesFilter = new FileFilter() {
    @Override
    public boolean accept(File file) {
        String fileName = file.getName();
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("'PREFIX_'uuuu-MM-dd_HH-mm-ss", Locale.ENGLISH);
        try {
            if (!LocalDateTime.parse(fileName, parser).toLocalDate().equals(LocalDate.now()))
                return false;
        } catch (DateTimeParseException e) {
            return false;
        }
        return true;
    }
};

The final step is to get the list of files,

File[] files = your-directory.listFiles(todaysFilesFilter);

Learn more about the modern Date-Time API from Trail: Date Time.

  • Related