Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FileBrowser {
public static void main(String[] args) {
List<String> folderList = findFoldersInDirectory("/home/prokash/Downloads");
System.out.println(folderList.size());
List<String> directoryList = findFilesInDirectory("/home/prokash/Downloads/Wallpapers");
System.out.println(directoryList.size());
List<File> fileList = findAllFoldersAndFilesInDirectory("/home/prokash/Downloads");
System.out.println(fileList.size());
}
private static List<File> findAllFoldersAndFilesInDirectory(String directoryPath) {
File topDirectory = new File(directoryPath);
List<File> foldersInDirectory = new ArrayList<>();
foldersInDirectory.add(topDirectory);
List<File> filesInDirectory = new ArrayList<>();
List<String> filterWildcards = new ArrayList<>();
filterWildcards.add("*.png");
filterWildcards.add("*.jpeg");
FileFilter typeFilter = new WildcardFileFilter(filterWildcards);
while (!foldersInDirectory.isEmpty()) {
List<File> subDirectories = new ArrayList<>();
for (File f : foldersInDirectory) {
subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter) DirectoryFileFilter.INSTANCE)));
filesInDirectory.addAll(Arrays.asList(f.listFiles(typeFilter)));
}
foldersInDirectory.clear();
foldersInDirectory.addAll(subDirectories);
}
return filesInDirectory;
}
private static List<String> findFoldersInDirectory(String directoryPath) {
File directory = new File(directoryPath);
FileFilter directoryFileFilter = File::isDirectory;
File[] directoryListAsFile = directory.listFiles(directoryFileFilter);
List<String> foldersInDirectory = new ArrayList<>();
if (directoryListAsFile != null) {
for (File directoryAsFile : directoryListAsFile) {
foldersInDirectory.add(directoryAsFile.getName());
}
}
return foldersInDirectory;
}
private static List<String> findFilesInDirectory(String directoryPath) {
File directory = new File(directoryPath);
FilenameFilter fileNameFilter = new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
if (name.toLowerCase().endsWith(".png")) {
return true;
} else if (name.toLowerCase().endsWith(".jpeg")) {
return true;
} else if (name.toLowerCase().endsWith(".pdf")) {
return true;
}
return false;
}
};
File[] directoryListAsFile = directory.listFiles(fileNameFilter);
List<String> filesInDirectory = new ArrayList<>();
if (directoryListAsFile != null) {
for (File directoryAsFile : directoryListAsFile) {
filesInDirectory.add(directoryAsFile.getName());
}
}
return filesInDirectory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment