Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a particular type of file in java

Tags:

java

file

image

I am selecting files in java using the following code:

  File folder = new File("path to folder");
  File[] listOfFiles = folder.listFiles();

Now what to do if I want to select only image files?

like image 754
insanity Avatar asked Jul 15 '13 11:07

insanity


1 Answers

Use one of the versions of File.listFiles() that accepts a FileFilter or FilenameFilter to define the matching criteria.

For example:

File[] files = folder.listFiles(
    new FilenameFilter()
    {
        public boolean accept(final File a_directory,
                              final String a_name)
        {
            return a_name.endsWith(".jpg");
            // Or could use a regular expression:
            //
            //     return a_name.toLowerCase().matches(".*\\.(gif|jpg|png)$");
            //
        };
    });
like image 84
hmjd Avatar answered Oct 27 '22 00:10

hmjd