简体   繁体   English

如何在 java 中获取文件夹大小

[英]How get folder size in java

I want get folder size and Rename it, if my folder size is more than 500 mbs then rename the folder, Download to MusicDownload我想获取文件夹大小并重命名它,如果我的文件夹大小超过 500 mbs 然后重命名文件夹,下载到 MusicDownload

import java.io.File;

class folderSize {
    private static long getFolderSize(File folder)
    {
        long length = 0;
        File[] files = folder.listFiles();
        int count = files.length;
        for (int i = 0; i < count; i++) {
            if (files[i].isFile()) 
              length += files[i].length();
            }
            else {
                length += getFolderSize(files[i]);
            }
        }
        return length;
   }
    public static void main(String[] args)

    {
        File file1 = new File("/storage/emulated/0/Download");
        long size = getFolderSize(file1);
        System.out.println("Size of " + file1 + " is "+ (long)size / (1024 * 1024)+ " MB");
    }
}

if You are using java8, can get the directory size as below如果您使用的是 java8,可以获得如下目录大小


     long size = 0;
      try (Stream<Path> walk = Files.walk(pathOfDirectory)) {

          size = walk
                  .filter(Files::isRegularFile)
                  .mapToLong(p -> {
                      try {
                          return Files.size(p);
                      } catch (IOException e) {
                          System.out.printf("Failed to get size of %s%n%s", p, e);
                          return 0L;
                      }
                  })
                  .sum();

      } catch (IOException e) {
          System.out.printf("IO errors %s", e);
      } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM