5

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?

messivanio
  • 2,263
  • 18
  • 24
insanity
  • 1,148
  • 6
  • 16
  • 29

3 Answers3

11

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)$");
            //
        };
    });
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • You will have to decide which is an image and what is not. Once you have done this, using a loop to filter is pretty easy. – Peter Lawrey Jul 15 '13 at 11:10
  • 1
    @PeterLawrey, _You will have to decide which is an image and what is not_, how is that different from _define the matching criteria_ ? The code that defines the match can be just as easily inserted into a filter or a loop, I am unsure how one is deemed better that the other. – hmjd Jul 15 '13 at 11:12
  • Using a loop is much shorter and simpler. – Peter Lawrey Jul 15 '13 at 12:09
  • See also [`ImageIO.getReaderFileSuffixes()`](http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#getReaderFileSuffixes%28%29) as mentioned in [this answer](http://stackoverflow.com/a/13521592/418556). – Andrew Thompson Jul 15 '13 at 12:34
4

You can use File.listFiles() with a FilenameFilter using ImageIO.getReaderFileSuffixes

File[] files = dir.listFiles(new FilenameFilter() {

   public boolean accept(File dir, String name) {
      List<String> images = Arrays.asList(ImageIO.getReaderFileSuffixes());

      String extension = "";
      int i = name.lastIndexOf('.');
      if (i > 0) {
         extension = name.substring(i+1);
      }

      return images.contains(extension.toLowerCase());
   }
});
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

May this code help you

         String imageExtension[] = new String[]{
            "jpg", "png", "bmp" // add more
        };
        File direcory = new File("path");
        File[] listFiles = direcory.listFiles();
        ArrayList<File> imageFileList = new ArrayList();
        for(File aFile : listFiles ) {
            // use FilenameUtils.getExtension from Apache Commons IO
            String extension = FilenameUtils.getExtension(aFile.getAbsolutePath());
            for(String ext: imageExtension) {
                if(extension.equals(ext)) {
                    imageFileList.add(aFile);
                    break;
                }
            }
        }
vels4j
  • 11,208
  • 5
  • 38
  • 63