0

The below code gives me the file path of the files in a directory that ends with "-path.mp4".But I need to get the file path of the files in a directory that doesn't end with "-path.mp4".

List<String> results = new ArrayList<String>();

File directory = new File(path);
FileFilter fileFilter = new WildcardFileFilter("*-path.mp4");

File[] files = directory.listFiles(fileFilter);

Arrays.sort(files, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.compare(f2.lastModified(), f1.lastModified());
        }
    });

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

return results;
a0x2
  • 1,995
  • 1
  • 18
  • 26

1 Answers1

0

You can easily write your own FileFilter in place of trying to make the WildcardFileFilter do something it wasn't meant to do, which is include files that match the wildcard(s) ...

FileFilter fileFilter = new FileFilter() {
    @Override
    public boolean accept(File pathname)
    {
        return ! pathname.getPath().endsWith("-path.mp4");
    }
};

This is very specific to your question, but you can see that it could be generalized, by returning true when a File does not match a regex.


In fact, you could just extend and override Apache's WildcardFileFilter — the basic idea is:

public class WildcardExclusionFilter extends WildcardFileFilter implements FileFilter
{
    public WildcardExclusionFilter(String glob)
    {
        super(glob);
    }

    @Override
    public boolean accept(File file)
    {
        // Return the Opposite of what the wildcard file filter returns,
        // to *exclude* matching files and *include* anything else.
        return ! super.accept(file);
    }
}

You may want to include more of the possible WildcardFileFilter constructors, and override the other form of their accept method, accept(File dir, String name) too.

Stephen P
  • 14,422
  • 2
  • 43
  • 67