import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DirectoryGrouper {
/**
* Groups entries of directories based on their file extensions.
* Handles edge cases like empty directories and directories with no files.
*
* @param rootDir The root directory to process.
* @return A map where keys are file extensions (e.g., ".txt") and values
* are lists of file paths with that extension. Returns an empty
* map if the root directory doesn't exist.
*/
public static Map<String, List<String>> groupEntriesByExtension(String rootDir) {
File root = new File(rootDir);
if (!root.exists()) {
System.err.println("Error: Root directory does not exist: " + rootDir);
return new HashMap<>(); // Return empty map if root doesn't exist
}
Map<String, List<String>> groupedFiles = new HashMap<>();
if (!root.isDirectory()) {
System.err.println("Error: Root is not a directory: " + rootDir);
return new HashMap<>();
}
File[] files = root.listFiles();
if (files == null) {
System.err.println("Error: Could not list files in: " + rootDir);
return new HashMap<>();
}
for (File file : files) {
if (file.isFile()) {
String extension = file.getName().split("\\.")[file.getName().split("\\.").length - 1]; // Extract extension
if (!extension.isEmpty()) {
groupedFiles.computeIfAbsent(extension, k -> new ArrayList<>()).add(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
// Recursive call to handle subdirectories (optional, can be removed for one-off)
//groupEntriesByExtension(file.getAbsolutePath());
}
}
return groupedFiles;
}
public static void main(String[] args) {
// Example usage:
String rootDirectory = "test_dir"; //Replace with your directory
File testDir = new File(rootDirectory);
if (!testDir.exists()) {
testDir.mkdir();
File file1 = new File(testDir, "file1.txt");
file1.createNewFile();
File file2 = new File(testDir, "file2.java");
file2.createNewFile();
File subdir = new File(testDir, "subdir");
subdir.mkdir();
File file3 = new File(subdir, "file3.txt");
file3.createNewFile();
}
Map<String, List<String>> grouped = groupEntriesByExtension(rootDirectory);
for (Map.Entry<String, List<String>> entry : grouped.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Add your comment