Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count images in a directory

I want to count how many image are in a directory. I have a copy of some code from internet which can detect the total file inside a directory.

import java.io.*;

public class CountFilesInDirectory {
      public static void main(String[] args) {
            File f = new File("/home/pc3/Documents/ffmpeg_temp/");
            int count = 0;
            for (File file : f.listFiles()) {
                    if (file.isFile()) {
                            count++;
                    }
            }
            System.out.println("Number of files: " + count);
    }
}

I wish to count a specific file type like jpg/txt. What should I do?

like image 315
Eric Avatar asked Dec 17 '22 01:12

Eric


1 Answers

Change this

if (file.isFile()) { 
  count++; 
} 

to

if (file.isFile() &&
    (file.getName().endsWith(".txt") || file.getName().endsWith(".jpg"))) { 
  count++; 
} 

What this code does is instead of just checking whether the entity denoted by file is actually a file (as opposed to a directory), you are also checking if its name ends with the particular extentions you are looking for

Note: you could use the String.toLowerCase() method to convert the name before comparison to be more accurate.

Update (based on comments): for a more OOP solution, you could implement the java.io.FilenameFilter interface and pass an instance of that to f.listFiles() -- thus enabling you to reuse that filter in another part of the program without much code repetition. If you use this approach, you need to move the endsWith logic to the FilenameFilter implementation

like image 197
Attila Avatar answered Dec 30 '22 01:12

Attila