java 使用 file[] 获取多个目录的文件夹大小

标签 java file loops

我在网上找到了一些代码,并尝试调整以浏览通过 fileChooser 选择的多个文件夹

public long getFolderSize(File[] selectedDirectories) {
 long foldersize = 0;

 for(int i = 0; i < selectedDirectories.length; i++){
  File[] currentFolder = selectedDirectories[i].listFiles();

  for (int q = 0; q < currentFolder.length; q++) {
   if (currentFolder[q].isDirectory()) {
    //if folder run self on q'th folder - in which case the files.length will be counted for the files inside
    foldersize += getFolderSize(currentFolder[q]);//<<the error is here 
   } else {
    //else get file size
    foldersize += currentFolder[q].length();
   }
  }
 return foldersize;
 }

}

错误位于:

getFolderSize(currentFolder[q]) 

因为我暗示它使用 File 而不是 File[] 但我坚持如何修复它

最佳答案

只需将签名从数组更改为可变参数:

public static long getgFolderSize(final File... selectedDirectories){
    long foldersize = 0;
    for(final File item : selectedDirectories){
        for(final File subItem : item.listFiles()){
            if(subItem.isDirectory()){
                foldersize += getFolderSize(subItem);
            } else{
                foldersize += subItem.length();
            }
        }
    }
    return foldersize;
}

现在您可以使用一个或多个文件或一组文件来调用该方法。

测试代码:(已更新,因此您可以看到,无论是否使用可变参数,它的工作原理都是相同的,如果您的主目录的子文件夹少于 5 个,则会失败)。

public static void main(final String[] args) throws Exception{
    final File homeFolder = new File(System.getProperty("user.home"));
    final File[] subFolders = homeFolder.listFiles(new FileFilter(){

        private int ct = 0;

        @Override
        public boolean accept(final File pathname){
            return pathname.isDirectory() && ct++ < 5;
        }
    });
    System.out.println("Folders to check:" + Arrays.toString(subFolders));
    long accumulated = 0l;

    for(final File file : subFolders){
        accumulated += getFolderSize(file);
    }
    final long allAtOnce = getFolderSize(subFolders);
    final long withVarArgs =
        getFolderSize(subFolders[0], subFolders[1], subFolders[2],
            subFolders[3], subFolders[4]);
    System.out.println("Accumulated: " + accumulated);
    System.out.println("All at once: " + allAtOnce);
    System.out.println("With varargs: " + withVarArgs);
}

(计算主目录中前 5 个文件夹的大小,应该适用于所有平台,如果主目录中的文件夹少于 5 个,则失败并显示 ArrayIndexOutOfBoundException)。

我的机器上的输出:

Folders to check:[/home/seanizer/Ubuntu One, /home/seanizer/Documents, /home/seanizer/.java, /home/seanizer/.mozilla, /home/seanizer/.evolution]
Accumulated: 1245886955
All at once: 1245886955
With varargs: 1245886955

关于java 使用 file[] 获取多个目录的文件夹大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4225697/

相关文章:

java - Arrays.fill() 和用于初始化链表数组的 for 循环之间的区别

MacOSX 上的 Java : how to access files in the bundle

java - 文本文件数组

c++ - 我怎样才能打印每个阶段下的数字并使其整齐地打印出来?

java - jMeter线程序列

java - SparkContext.wholeTextFiles之后如何单独处理多个文件?

java - 如何检查文本文件是否包含字符串?

arrays - 遍历不同大小的数组

java - 如何在处理中的不同时间间隔后触发不同的事件?

java - 调试时是否可以更改 android 上的所有者(用户)?