I’ve written a small function to calculate the size of all the files in a directory. The actual function does a lot more but this example has been used for brevity.
This works and walking the directory recursively is easy enough but I’d like to exclude all the filenames that have already been processed. I’d like to keep track of all the filenames in a List so that before getting the size of a file, I check if it exists in the List and if it does, it should be excluded. I don’t want any MD5 checksums or anything. Filenames are good enough for my situation.
Since I can only return one value from a function and Java doesn’t allow pass-by-reference, I’m pretty lost as to what is the best way to implement this. Here’s my code:
public static Long getFileSize(File dirDirectory) {
Long lngSize = new Long(0);
for (File filItem : dirDirectory.listFiles()) {
if (filItem.isDirectory()) {
lngSize += getFileSize(filItem);
}
else {
//Is a file with the same filename alrwady been calculated
//then exclude it
//else
//include it.
lngSize += filItem.length();
}
}
return lngSize;
}
Don’t use a
List, use aHashSet. A list will useO(n)lookups to see if the file is there, whereas aHashSetwill useO(1).By making the method public and the helper function private, you don’t expose the
HashSetimplementation to the rest of your program (which doesn’t and shouldn’t care about it).