private SubDirsAndSize getSubDirsAndSize(File file){ long total = 0; List<File> subDirs = new ArrayList<File>(); if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if (child.isFile()) total += child.length(); else subDirs.add(child); } } } returnnew SubDirsAndSize(total, subDirs); }
privatelonggetFileSize(File file)throws Exception { finalint cpuCore = Runtime.getRuntime().availableProcessors(); finalint poolSize = cpuCore + 1; ExecutorService service = Executors.newFixedThreadPool(poolSize); long total = 0; List<File> directories = new ArrayList<File>(); directories.add(file); SubDirsAndSize subDirsAndSize = null; try { while (!directories.isEmpty()) { List<Future<SubDirsAndSize>> partialResults = new ArrayList<Future<SubDirsAndSize>>(); for (final File directory : directories) { partialResults.add(service.submit(new Callable<SubDirsAndSize>() { @Override public SubDirsAndSize call()throws Exception { return getSubDirsAndSize(directory); } })); } directories.clear(); for (Future<SubDirsAndSize> partialResultFuture : partialResults) { subDirsAndSize = partialResultFuture.get(100, TimeUnit.SECONDS); total += subDirsAndSize.size; directories.addAll(subDirsAndSize.subDirs); } } return total; } finally { service.shutdown(); } }
publicstaticvoidmain(String[] args)throws Exception { for (int i = 0; i < 10; i++) { finallong start = System.currentTimeMillis(); long total = new FileSizeCalc().getFileSize(new File("D:/DevTools")); finallong end = System.currentTimeMillis(); System.out.format("文件夹大小: %dMB%n", total / (1024 * 1024)); System.out.format("所用时间: %.3fs%n", (end - start) / 1.0e3); } } }