1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. public class DirectoryGrouper {
  7. /**
  8. * Groups entries of directories based on their file extensions.
  9. * Handles edge cases like empty directories and directories with no files.
  10. *
  11. * @param rootDir The root directory to process.
  12. * @return A map where keys are file extensions (e.g., ".txt") and values
  13. * are lists of file paths with that extension. Returns an empty
  14. * map if the root directory doesn't exist.
  15. */
  16. public static Map<String, List<String>> groupEntriesByExtension(String rootDir) {
  17. File root = new File(rootDir);
  18. if (!root.exists()) {
  19. System.err.println("Error: Root directory does not exist: " + rootDir);
  20. return new HashMap<>(); // Return empty map if root doesn't exist
  21. }
  22. Map<String, List<String>> groupedFiles = new HashMap<>();
  23. if (!root.isDirectory()) {
  24. System.err.println("Error: Root is not a directory: " + rootDir);
  25. return new HashMap<>();
  26. }
  27. File[] files = root.listFiles();
  28. if (files == null) {
  29. System.err.println("Error: Could not list files in: " + rootDir);
  30. return new HashMap<>();
  31. }
  32. for (File file : files) {
  33. if (file.isFile()) {
  34. String extension = file.getName().split("\\.")[file.getName().split("\\.").length - 1]; // Extract extension
  35. if (!extension.isEmpty()) {
  36. groupedFiles.computeIfAbsent(extension, k -> new ArrayList<>()).add(file.getAbsolutePath());
  37. }
  38. } else if (file.isDirectory()) {
  39. // Recursive call to handle subdirectories (optional, can be removed for one-off)
  40. //groupEntriesByExtension(file.getAbsolutePath());
  41. }
  42. }
  43. return groupedFiles;
  44. }
  45. public static void main(String[] args) {
  46. // Example usage:
  47. String rootDirectory = "test_dir"; //Replace with your directory
  48. File testDir = new File(rootDirectory);
  49. if (!testDir.exists()) {
  50. testDir.mkdir();
  51. File file1 = new File(testDir, "file1.txt");
  52. file1.createNewFile();
  53. File file2 = new File(testDir, "file2.java");
  54. file2.createNewFile();
  55. File subdir = new File(testDir, "subdir");
  56. subdir.mkdir();
  57. File file3 = new File(subdir, "file3.txt");
  58. file3.createNewFile();
  59. }
  60. Map<String, List<String>> grouped = groupEntriesByExtension(rootDirectory);
  61. for (Map.Entry<String, List<String>> entry : grouped.entrySet()) {
  62. System.out.println(entry.getKey() + ": " + entry.getValue());
  63. }
  64. }
  65. }

Add your comment