Search code examples
javafilefilteringapache-commonsprefix

Filtering Files with prefix as well as age of file


I am trying to retrieve all the files that start with "Sample" and also all those that were created/modified at the same time as that of given timestamp or before the time stamp. I have to get the latest file from these.

I could filter the files with the prefix but i am not sure of how to add one more filter i.e. timestamp.

I initially used LastModifiedFileComparator.LASTMODIFIED_REVERSE but it checks for all files not according to timestamp. So to do these i need filtering on timestamp as well. I have an idea that AgeFileFilter and PrefixFileFilter classes of apache commons will help me but i am unable put together both the classes.

How do i achieve this?

Below is my code

public void searchFiles(File path) {
    FilenameFilter prefix = new FilenameFilter() {
        public boolean accept(File directory, String filename) {
             return filename.startsWith("Sample");
        }
    };

    SimpleDateFormat dateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

    File[] files1 = path.listFiles(prefix);
    Arrays.sort(files1, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
    System.out.println("\nThe latest file is: "+files1[0]+ " & is updated on: " + dateTime.format(files1[0].lastModified()));
}

Thanks in advance


Solution

  • You need a filter that can compare filenames and modification times too. FilenameFilter cannot do this, but FileFilter can, for example:

    FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().startsWith("Sample") && pathname.lastModified() > LASTMODIFIED_LIMIT;
        }
    };
    

    The same thing can be written shorter with a lambda:

    FileFilter filter = pathname -> pathname.getName().startsWith("Sample")
            && pathname.lastModified() > LASTMODIFIED_LIMIT;