Java如何獲取目錄的大小?

2019-10-16 22:29:46

在Java程式中,如何獲取目錄的大小?

以下範例顯示如何通過FileUtils類的FileUtils.sizeofDirectory(File Name)方法獲取目錄的大小。

註:commons-io-2.5.jar包的下載地址:http://commons.apache.org/proper/commons-io/download_io.cgi

package com.yiibai;

import java.io.File;
import org.apache.commons.io.FileUtils;

public class DirectorySize {
    public static void main(String[] args) {
        String dir = "F:/worksp/javaexamples";
        long size = FileUtils.sizeOfDirectory(new File(dir));
        System.out.println("Size of " + dir + ": " + size + " bytes");
    }
}

執行上面範例程式碼,得到以下結果 -

Size of F:/worksp/javaexamples: 16935629 bytes

範例-2

以下是Java中獲取目錄的大小的另一個範例。

package com.yiibai;

import java.io.File;
import java.util.ArrayList;

public class DirectorySize2 {
    public static void main(String[] args) {
        String dir = "F:\\worksp\\javaexamples\\java_directories";
        long folderSize = findSize(dir);
        System.out.println("Size of " + dir + " in byte :" + folderSize);
    }

    public static long findSize(String path) {
        long totalSize = 0;
        ArrayList<String> directory = new ArrayList<String>();
        File file = new File(path);

        if (file.isDirectory()) {
            directory.add(file.getAbsolutePath());
            while (directory.size() > 0) {
                String folderPath = directory.get(0);
                System.out.println("Size of this :" + folderPath);
                directory.remove(0);
                File folder = new File(folderPath);
                File[] filesInFolder = folder.listFiles();
                int noOfFiles = filesInFolder.length;

                for (int i = 0; i < noOfFiles; i++) {
                    File f = filesInFolder[i];
                    if (f.isDirectory()) {
                        directory.add(f.getAbsolutePath());
                    } else {
                        totalSize += f.length();
                    }
                }
            }
        } else {
            totalSize = file.length();
        }
        return totalSize;
    }
}

執行上面範例程式碼,得到以下結果 -

Size of this :F:\worksp\javaexamples\java_directories
Size of this :F:\worksp\javaexamples\java_directories\bin
Size of this :F:\worksp\javaexamples\java_directories\dir11
Size of this :F:\worksp\javaexamples\java_directories\src
Size of this :F:\worksp\javaexamples\java_directories\bin\com
Size of this :F:\worksp\javaexamples\java_directories\dir11\dir12
Size of this :F:\worksp\javaexamples\java_directories\src\com
Size of this :F:\worksp\javaexamples\java_directories\bin\com\yiibai
Size of this :F:\worksp\javaexamples\java_directories\dir11\dir12\dir13
Size of this :F:\worksp\javaexamples\java_directories\src\com\yiibai
Size of F:\worksp\javaexamples\java_directories in byte :26713