0

I have a LinkedList of files which I populated using the following line:

File file = new File(directoryPath);
List<File> filesList = new LinkedList<File>(Arrays.asList(file.listFiles()));

This gets me all the files in given directoryPath string.

I then have an Array of the file extensions that are allowed and would like to delete any file (not directory) that's inside which doesn't match up.

String[] file_ext = new String[] {"ext1", "ext2", "ext3"};

How can I proceed to implement this?

Linkandzelda
  • 611
  • 14
  • 24

4 Answers4

1

You can use something like this

final String[]  file_ext = new String[] {"ext1", "ext2", "ext3"};

FilenameFilter filter = new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
            for(int i=file_ext.length-1;i>=0;i--)
                if( name.endsWith( "." + file_ext[i]) )
                    return true;
            return false;
        }
    };

File file = new File(directoryPath);
List<File> filesList = new LinkedList<File>(Arrays.asList(file.listFiles(filter)));

Updated: As per 'Borsi the Spider' comment, to avoid false matches such as files.notext1, the searching matches the . character as well

Akash
  • 4,956
  • 11
  • 42
  • 70
0
  1. Take list of files and check if they names ends with any ext from file_ext, if yes, add them to list of filesToDelete
  2. Delete files from filesToDelete list.
MGorgon
  • 2,547
  • 23
  • 41
0

Use a FilenameFilter, an example can be found here

Community
  • 1
  • 1
earcam
  • 6,662
  • 4
  • 37
  • 57
0

Use a FileNameExtensionFilter

final FileNameExtensionFilter fnef = new FileNameExtensionFilter("", "ext1", "ext2", "ext3");
final List<File> files = new LinkedList<>();
for(final File f : new File(directoryPath).listFiles()) {
    if(fnef.accept(f)) files.add(f);
}

This is from Swing but it does exactly what you want and it doesn't have any dependencies on the EDT or anything odd.

You could even wrap the FileNameExtensionFilter in a FileFilter façade and make it a one-liner:

final List<File> filesList = new LinkedList<>(Arrays.asList(new File(directoryPath).listFiles(new FileFilter() {
    final FileNameExtensionFilter fnef = new FileNameExtensionFilter("", "ext1", "ext2", "ext3");

    @Override
    public boolean accept(File pathname) {
        return fnef.accept(pathname);
    }
})));
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166