我正在尝试获取目录的长度(文件大小),并且我已经使用以下递归方法来执行此操作,但是当我将new File("C:\\Users\\UserName\\Desktop")
作为参数传递时,我得到了一些非常奇怪的结果。
static long totalLength = 0;
// Method to get the size of a folder and its contents
private static long getFolderSize(File folder){
if(folder.isDirectory()){
File[] contents = folder.listFiles();
for(File current : contents){
if(current.isDirectory()){
totalLength = totalLength +getFolderSize(current);
}
totalLength = totalLength + current.length();
}
}
return totalLength;
}
有趣的是,当我将它们传递给方法时,桌面上的某些文件夹会返回预期的结果。我只是无法弄清楚为什么:我已经对各个文件的长度进行了一些调试,但没有一个看起来是负面的,但我仍然有时会得到负面结果!
任何想法将不胜感激!提前致谢
答案 0 :(得分:3)
您在isDirectory()
if语句中缺少else {}块。因此,您在目录上调用File.length()
,根据文档未指定该目录。它可能会返回一个负值。
此处File.length()
的文档:
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length()
您的代码应该是:
if(current.isDirectory()) {
totalLength = totalLength +getFolderSize(current, initial);
} else {
totalLength = totalLength + current.length();
}
答案 1 :(得分:3)
为什么不使用已经内置的已建立的库,例如:
还有测试来涵盖这样的案例。
答案 2 :(得分:0)
我认为这在风格上更好:
private static long getFolderSize(File f) {
if(!f.isDirectory()) return f.length();
long totalLength = 0;
for (File current : f.listFiles()) {
totalLength += getFolderSize(current);
}
return totalLength;
}