How to filter folders(Directories and Sub-Dir) based on specific file's extension in java..?
Okay i read a lot of stuff and i failed to figure out that how to filter folders(directories and sub-dir) based on file’s extension for example i want the list of folders(Directories and Sub-dir) that contains only ".mp3" or ".mp4" files and i don’t want to use Walk.Tree, if there’s any possible way through "filenameFilter" or any other way except Walk.tree method.
this is the code that i have tried so far, no error but also not filtering specific file’s folders. it shows all the folders.
Thanks in Advance.
File[] ff = f.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".mp3") || new File(dir.toPath().toString(),name).isDirectory(); } });
Here is a simple console application.
The algorithm goes like this:
- First recursively search from specified root folder for all files with mp3 extension and keep adding them to a list.
- If this list happens to be empty, return.
- Else, for each of these mp3 files, recursively find their parent folders until you reach root folder and keep storing these parent folders in a set to avoid duplicate search.
- Now print out all those valid folders starting from root.
public class MyApp { public static void main(String[] args) { File rootDir = new File("src/main/resources/dir1"); List<File> filesListWithValidExtension = new ArrayList<>(); recursiveSearch(rootDir, filesListWithValidExtension); if (filesListWithValidExtension.size() == 0) { System.out.println("Specified root directory has no file with mp3 extension"); return; } Set<File> requiredFolders = new HashSet<>(); for (File fileWithValidExtension : filesListWithValidExtension) { File parent; do { parent = fileWithValidExtension.getParentFile(); if (requiredFolders.contains(parent)) { break; } else { requiredFolders.add(parent); fileWithValidExtension = parent; } } while (!parent.getPath().equals(rootDir.getPath())); } System.out.println("Printing folders (from root) containing mp3 files"); recursivePrint(rootDir, requiredFolders); } private static void recursiveSearch(File file, List<File> filesListWithvalidExtension) { if (!file.exists()) { return; } if (file.isDirectory()) { for (File f : file.listFiles()) { recursiveSearch(f, filesListWithvalidExtension); } } if (file.getName().toLowerCase().endsWith(".mp3")) { filesListWithvalidExtension.add(file); } } private static void recursivePrint(File file, Set<File> requiredFolders) { if (!requiredFolders.contains(file)) { return; } System.out.println(file.getPath()); for (File f : file.listFiles()) { recursivePrint(f, requiredFolders); } } }
This program outputs like:
Printing folders (from root) containing mp3 files src/main/resources/dir1 src/main/resources/dir1/dir12 src/main/resources/dir1/dir11 src/main/resources/dir1/dir11/dir111