在Java中获取目录的大小
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;
}
}
/**
*
* @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;
}
}