javafilterfilelist

Find latest file that matches pattern in folder


I'm writing a method that will take 2 inputs:

  1. String name

  2. String path

Then output the latest pdf(with pdf as extension) filename that start with name (which is a variable) and is in the path.

I am using:

public String getLatestMatchedFilename(String path, String name){
    File dir=new File(path);    
    File[] files = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith();
        }
    });
}

However, I don't know how to pass the the value in name into the accept method, since it's a variable and changes everytime.


Solution

  • Change name to one of the variables called name. Mark the String name parameter (or whatever name it will have) in your method with final in order to be used inside an anonymous class and use it directly.

    Here is how the code should look:

    public String getLatestMatchedFilename(String path, final String name) {
        File dir = new File(path);    
        File[] files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String nameFilter) {
                return nameFilter.startsWith(name);
            }
        });
        // rest of your code ...
    }