1. import java.io.File;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. class DirectoryAggregator {
  5. /**
  6. * Aggregates values (file sizes) of directories for sandbox usage.
  7. * Handles edge cases like non-existent directories and permission issues.
  8. *
  9. * @param rootDir The root directory to aggregate from.
  10. * @return A map where keys are directory paths and values are their total sizes in bytes.
  11. * Returns an empty map if the rootDir is null or an invalid path.
  12. */
  13. public static Map<String, Long> aggregateDirectorySizes(String rootDir) {
  14. Map<String, Long> directorySizes = new HashMap<>();
  15. if (rootDir == null || rootDir.isEmpty()) {
  16. return directorySizes; // Handle null or empty rootDir
  17. }
  18. File root = new File(rootDir);
  19. if (!root.exists()) {
  20. System.err.println("Error: Directory does not exist: " + rootDir);
  21. return directorySizes; // Handle non-existent directory
  22. }
  23. if (!root.isDirectory()) {
  24. System.err.println("Error: Not a directory: " + rootDir);
  25. return directorySizes; // Handle files instead of directories
  26. }
  27. File[] files = root.listFiles();
  28. if (files == null) {
  29. System.err.println("Error: Could not list files in directory: " + rootDir);
  30. return directorySizes; // Handle permission issues or other listing errors
  31. }
  32. for (File file : files) {
  33. if (file.isDirectory()) {
  34. // Recursively aggregate sizes of subdirectories
  35. Map<String, Long> subDirSizes = aggregateDirectorySizes(file.getAbsolutePath());
  36. for (Map.Entry<String, Long> entry : subDirSizes.entrySet()) {
  37. directorySizes.put(entry.getKey(), directorySizes.getOrDefault(entry.getKey(), 0L) + entry.getValue());
  38. }
  39. } else if (file.isFile()) {
  40. directorySizes.put(file.getAbsolutePath(), file.length());
  41. }
  42. }
  43. return directorySizes;
  44. }
  45. public static void main(String[] args) {
  46. // Example usage:
  47. String sandboxDir = "test_sandbox"; // Replace with your desired directory
  48. // Create a test directory structure if it doesn't exist
  49. File sandbox = new File(sandboxDir);
  50. if (!sandbox.exists()) {
  51. sandbox.mkdir();
  52. File subdir1 = new File(sandboxDir, "subdir1");
  53. subdir1.mkdir();
  54. File file1 = new File(sandboxDir, "file1.txt");
  55. file1.createNewFile();
  56. File file2 = new File(sandboxDir, "subdir1", "file2.txt");
  57. file2.createNewFile();
  58. }
  59. Map<String, Long> sizes = aggregateDirectorySizes(sandboxDir);
  60. for (Map.Entry<String, Long> entry : sizes.entrySet()) {
  61. System.out.println("Directory: " + entry.getKey() + ", Size: " + entry.getValue() + " bytes");
  62. }
  63. }
  64. }

Add your comment