在Java中获取目录的大小

Iacob posted @ 2008年4月04日 02:48 in Java with tags java 目录 大小 J2SE , 3587 阅读
import java.io.File;

/**
 *
 * @author Iacob
 */

public class Main {

    public static void main(String args[]) {
       
        long size = 0;
       
        File dir = new File("C:\\"); // 选定要统计的目录
       
        System.out.println(calculateDirectorySize(dir)); // 统计并打印结果
    }
   
    public static long calculateDirectorySize(File dir) {
       
        if (dir == null) {
           
            throw new RuntimeException("Target must not be null.");
        }
       
        if (!dir.isDirectory()) {
           
            throw new RuntimeException("Target must be a directory.");
        }
       
        long directorySize = 0;
       
        File[] files = dir.listFiles();
       
        for (File file:files) {
           
            if (file.isFile()) {
               
                directorySize += file.length();
            }else if (file.isDirectory()) {
               
                directorySize += file.length();
               
                directorySize += calculateDirectorySize(file); // 如果遇到目录则通过递归调用继续统计
            }
        }
       
        return directorySize;
    }
}
 
Avatar_small
KVS 2nd Class Model 说:
2022年9月29日 21:02

Every year the Kendriya Vidyalaya Sangathan Subject experts are provided those practice model question bank to their students for practicing subject most important questions of Term-1, Term-2, Term-3, KVS 2nd Class Model Paper Term-4 exams along with school-level exams at all regions of the country, and this year also provided the KVS 2nd Class Model Paper 2023 with Suggested Answer Solutions to all subjects in Chapter wise to every lesson. Every year the Kendriya Vidyalaya Sangathan Subject experts are provided those practice model question bank to their students for practicing subject most important questions of Term-1, Term-2.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter