import java.io.File;
import java.util.Scanner;
public class Test1 {
/**
*
* @param args
*
* 需求:1,從鍵盤接收一個檔案夾路徑,統計該檔案夾大小
*
* 從鍵盤接收一個檔案夾路徑
*
* 1,建立鍵盤錄入對象
*
* 2,定義一個無限循環
*
* 3,将鍵盤錄入的結果存儲并封裝成File對象
*
* 4,對File對象判斷
*
* 5,将檔案夾路徑對象傳回
*
* 統計該檔案夾大小
*
* 1,定義一個求和變量
*
* 2,擷取該檔案夾下所有的檔案和檔案夾listFiles();
*
* 3,周遊數組
*
* 4,判斷是檔案就計算大小并累加
*
* 5,判斷是檔案夾,遞歸調用
*/
public static void main(String[] args) {
// File dir = new File("F:\\day06");
// System.out.println(dir.length()); //直接擷取檔案夾的結果是0
File dir = getDir();
System.out.println(getFileLength(dir));
}
/*
*
* 從鍵盤接收一個檔案夾路徑
*
* 1,傳回值類型File
*
* 2,參數清單無
*/
public static File getDir() {
// 1,建立鍵盤錄入對象
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個檔案夾路徑:");
// 2,定義一個無限循環
while (true) {
// 3,将鍵盤錄入的結果存儲并封裝成File對象
String line = sc.nextLine();
File dir = new File(line);
// 4,對File對象判斷
if (!dir.exists()) {
System.out.println("您錄入的檔案夾路徑不存在,請輸入一個檔案夾路徑:");
} else if (dir.isFile()) {
System.out.println("您錄入的是檔案路徑,請輸入一個檔案夾路徑:");
} else {
// 5,将檔案夾路徑對象傳回
return dir;
}
}
}
/*
*
* 統計該檔案夾大小
*
* 1,傳回值類型long
*
* 2,參數清單File dir
*/
public static long getFileLength(File dir) { // dir = F:\day06\day07
// 1,定義一個求和變量
long len = 0;
// 2,擷取該檔案夾下所有的檔案和檔案夾listFiles();
File[] subFiles = dir.listFiles(); // day07 Demo1_Student.class
// Demo1_Student.java
// 3,周遊數組
for (File subFile : subFiles) {
// 4,判斷是檔案就計算大小并累加
if (subFile.isFile()) {
len = len + subFile.length();
// 5,判斷是檔案夾,遞歸調用
} else {
len = len + getFileLength(subFile);
}
}
return len;
}
}