public class Test02 {
/**
*(1)从键盘接收一个文件夹路径,统计该文件夹大小
*/
public static void main(String[] args) {
File file =getFile();
long length =getLength(file);
System.out.println(length);
}
private static long getLength(File file) {
long sum =0;
File[] subfiles =file.listFiles();
for (File subfile : subfiles) {
if (subfile.isFile()) {
sum =sum +subfile.length();
}else{
sum += getLength(subfile);
}
}
return sum;
}
public static File getFile() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个文件夹路径");
while (true) {
String line =sc.nextLine();
File file = new File(line);
if (!file.exists()) {
System.out.println("文件夹不存在,请重新录入");
}else if (file.isFile()) {
System.out.println("您录入的是文件路径,请重新录入文件夹路径");
}else{
return file;
}
}
}
}
|