public static void main(String[] args) throws IOException {
File dir = Dir();
double d = Length(dir)/1024/1024;
System.out.println("文件的大小为"+ d +"MB");
}
public static File Dir() {//获取文件夹路径方法
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
File dir = new File(line);
while (true) {
if (!dir.exists()) {
System.out.println("路径不存在,请重新输入: ");
} else if (dir.isFile()) {
System.out.println("请输入一个文件夹路径");
} else {
return dir;
}
}
}
public static long Length(File dir) {//计算文件夹大小方法
long length = 0;
File[] files = dir.listFiles();
for (File file : files) {
if(file.isFile()) {
length+=file.length();
}else {
length += Length(file);//如果是文件夹,则递归调用Length方法
}
}
return length;
}
目标文件夹属性:
为6366213字节.
运行结果: