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?
Change this
to
What this code does is instead of just checking whether the entity denoted by
fileis actually a file (as opposed to a directory), you are also checking if its name ends with the particular extentions you are looking forNote: 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.FilenameFilterinterface and pass an instance of that tof.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 theendsWithlogic to theFilenameFilterimplementation