在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