Java递归计算一个文件夹所有文件大小
import java.io.File; import java.util.Scanner; public class Demo1 { public static void main(String[] args) { File dirFile = getDirFile(); System.out.println(countDirFile(dirFile)); } /** * 计算文件夹大小 */ public static long countDirFile(File dirFile) { long num = 0L; File[] listFiles = dirFile.listFiles(); for (File subFile : listFiles) { if (subFile.isFile()) { num = num + subFile.length(); } else { num = num + countDirFile(subFile); } } return num; } /** * 获取文件夹路径 */ public static File getDirFile() { Scanner scanner = new Scanner(System.in); System.out.println("请输入文件路径"); while (true) { String line = scanner.nextLine(); File dirFile = new File(line); if (dirFile.isDirectory()) { return dirFile; } else { System.out.println("输入错误,重新输入"); } } } }