上篇博客刚记录java读取文件目录返回树形结构,以提供给前端进行渲染展示,这次来记录下统计文件的大小和文件的个数。
package cn.cnic.instdb.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* @author wdd
* @version 1.0
* @date 2021/11/29 14:57
*/
public class FileCounter {
//用于储存找到的每一个文件
ArrayList<File> fileList;
//根目录
File root;
public Map getFileInfo(String pathName,String fileFilter) {
Map<String, Object> map = new HashMap<>();
root = new File(pathName);
fileList = new ArrayList<>();
ArrayList arrayList = countFiles(fileFilter);
map.put("fileCount", arrayList.size());
map.put("storageNum", lengthFiles());
return map;
}
//递归算法查找文件
public ArrayList countFiles(String fileFilter) {
File[] files = root.listFiles();
int length = files.length;
for (int i = 0; i < length; i++) {
if(fileFilter.equals(files[i].getName())){
continue;
}
if (files[i].isDirectory()) {
root = files[i];
countFiles(fileFilter);
} else {
fileList.add(files[i]);
}
}
return fileList;
}
//统计文件个数和总的大小
public long lengthFiles() {
long totalSize = 0;
for (int i = 0; i < fileList.size(); i++) {
//返回由此文件的长度,字节为单位
totalSize += fileList.get(i).length();
}
return totalSize;
}
public static void main(String[] args) {
FileCounter counter = new FileCounter();
Map fileInfo = counter.getFileInfo("D:\\123test","11111.java");
System.out.println(fileInfo);
}
}