- Given input directory containing different files like image, video, text, csv, json etc.
- We would like to list files having specified file extensions.
- List video files having file extensions “avi”, “wmv” and “mov”.
- List image files having file extensions “jpg”, “png” and “tif”.
- List video files having file extension “txt”.
- We will filter out the files by creating custom class implementing FilenameFilter interface.
1. Program: list multiple files like image, video, text (FilenameFilter/java)
package org.learn;
import java.io.File;
import java.io.FilenameFilter;
public class ListImgVidTxtFiles {
public static void main(String[] args) {
File directory = new File("d:/repo");
String[] videoFileFilters = {"avi", "wmv", "mov"};
String[] imageFileFilters = {"jpg", "png", "tif"};
String[] txtFileFilters = {"txt"};
System.out.println("1. Listing video files present in input directory");
printFiles(directory, videoFileFilters);
System.out.println("\n2. Listing image files present in input directory");
printFiles(directory, imageFileFilters);
System.out.println("\n3. Listing text files present in input directory");
printFiles(directory, txtFileFilters);
}
private static void printFiles(File inputDirectory, String[] filters) {
File[] files = inputDirectory.listFiles(new FileFilter(filters));
for (File file : files) {
System.out.println(file.getName());
}
}
}
class FileFilter implements FilenameFilter {
private String[] allowedExtensions = null;
public FileFilter(String[] allowedExtensions) {
this.allowedExtensions = allowedExtensions.clone();
}
@Override
public boolean accept(File dir, String name) {
String fileExt = name.substring(name.lastIndexOf(".") + 1);
for (String imgExt : allowedExtensions) {
if (imgExt.compareToIgnoreCase(fileExt) == 0)
return true;
}
return false;
}
}
2. Input directory containing file formats like image, videos, text etc.
3. Output: list multiple image, video, text files (Java/FilenameFilter)
1. Listing video files present in input directory
Citizen Kane.wmv
Pulp Fiction.mov
The Dark Knight.avi
2. Listing image files present in input directory
Harley.tif
Royal.png
Title.jpg
Tulips.jpg
3. Listing text files present in input directory
applicationLogs.txt
sampleFile.txt