package com.sdy.Test;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Test5 {
/**
* @throws IOException
* @从键盘接收一个文件夹路径,统计该文件夹大小
*/
public static void main(String[] args) throws IOException {
File dir = grtDir();
long size = countLength(dir);
System.out.println("文件夹大小为" + size + "个字节");
}
private static long countLength(File dir) {
long count = 0;
File[] fis = dir.listFiles();
for (File file : fis) {
if (file.isDirectory()) {
count += countLength(file);
} else {
count += file.length();
}
}
return count;
}
private static File grtDir() throws IOException {
System.out.println("请输入正确的文件夹路径: ");
Scanner sc = new Scanner(System.in);
while (true) {
String str = sc.nextLine();
File file = new File(str);
if (!file.exists()) {
System.out.println("文件夹路径错误!");
continue;
} else if (file.isFile()) {
System.out.println("输入的是文件,不是文件夹!");
continue;
} else {
return file;
}
}
}
} |
|