import java.io.File;
import java.util.HashMap;
import java.util.Map;
class DirectoryAggregator {
/**
* Aggregates values (file sizes) of directories for sandbox usage.
* Handles edge cases like non-existent directories and permission issues.
*
* @param rootDir The root directory to aggregate from.
* @return A map where keys are directory paths and values are their total sizes in bytes.
* Returns an empty map if the rootDir is null or an invalid path.
*/
public static Map<String, Long> aggregateDirectorySizes(String rootDir) {
Map<String, Long> directorySizes = new HashMap<>();
if (rootDir == null || rootDir.isEmpty()) {
return directorySizes; // Handle null or empty rootDir
}
File root = new File(rootDir);
if (!root.exists()) {
System.err.println("Error: Directory does not exist: " + rootDir);
return directorySizes; // Handle non-existent directory
}
if (!root.isDirectory()) {
System.err.println("Error: Not a directory: " + rootDir);
return directorySizes; // Handle files instead of directories
}
File[] files = root.listFiles();
if (files == null) {
System.err.println("Error: Could not list files in directory: " + rootDir);
return directorySizes; // Handle permission issues or other listing errors
}
for (File file : files) {
if (file.isDirectory()) {
// Recursively aggregate sizes of subdirectories
Map<String, Long> subDirSizes = aggregateDirectorySizes(file.getAbsolutePath());
for (Map.Entry<String, Long> entry : subDirSizes.entrySet()) {
directorySizes.put(entry.getKey(), directorySizes.getOrDefault(entry.getKey(), 0L) + entry.getValue());
}
} else if (file.isFile()) {
directorySizes.put(file.getAbsolutePath(), file.length());
}
}
return directorySizes;
}
public static void main(String[] args) {
// Example usage:
String sandboxDir = "test_sandbox"; // Replace with your desired directory
// Create a test directory structure if it doesn't exist
File sandbox = new File(sandboxDir);
if (!sandbox.exists()) {
sandbox.mkdir();
File subdir1 = new File(sandboxDir, "subdir1");
subdir1.mkdir();
File file1 = new File(sandboxDir, "file1.txt");
file1.createNewFile();
File file2 = new File(sandboxDir, "subdir1", "file2.txt");
file2.createNewFile();
}
Map<String, Long> sizes = aggregateDirectorySizes(sandboxDir);
for (Map.Entry<String, Long> entry : sizes.entrySet()) {
System.out.println("Directory: " + entry.getKey() + ", Size: " + entry.getValue() + " bytes");
}
}
}
Add your comment