简体   繁体   中英

Get list of image filenames in directory that match specific String in filename

I have a directory of +- 5000 images. Filenames are build according to a products ID.

Example -> product with id 'EAN456' Images that belong to this product in the image directory -> EAN456.jpg, EAN456-1.jpg, EAN456-2.jpg

So through Java code I want to retrieve all the images with filenames that match the product id. In this example EAN456.jpg, and all the sequenced images (divided with a '-') EAN456-1.jpg EAN456-2.jpg

I know you can loop the directory in java and check each Filename to see if it has the ID in the filename... But looping so many files seems not the best way...

private void getImagesFromFolder(String directoryName)
{
    File directory = new File(directoryName);
    File [] files = directory.listFiles();
    //
    for (File file : files){
        if(file.isFile()) {
            // check if filename equals product id ...
        }            
    }    
}

Can anybody help me in a good approach? Thanks!

You can just get files that their name start with pruduct id using FilenameFilter like this:

File dir = new File(".");
    File [] files = dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith("EAN456");
        }
    });

To avoid looping over many files, you could just try to read the files. Get EAN456, then continue with EAN456-1, EAN456-2 and so on, until a file does not exist. Gives you all the files and you don't have to loop.

Using Apache Commons IO FileUtils.listFiles

(List<File>) FileUtils.listFiles(directory, new RegexFileFilter(product.id + "[-]*[0-9]*\\.jpg"), DirectoryFileFilter.DIRECTORY);

UPDATE:

for all types of extensions

(List<File>) FileUtils.listFiles(directory, new RegexFileFilter(product.id + "[-]*[0-9]*\\.(.+)", DirectoryFileFilter.DIRECTORY);

This will match files with all extensions. files without any extension will be ignored

If you have a list of file extensions that you would like to list, then use the following regex

product.id + [-]*[0-9]*\\.(png|jpg|jpeg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM