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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With