主递归方法
public static void readCurrentAllFile(File root, JSONArray array) {
if (root.exists()) {
if (root.isDirectory()) {
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() && !files[i].isHidden()) {
array.add(readFile(files[i]));
} else if (files[i].isDirectory() && !files[i].isHidden()) {
readCurrentAllFile(files[i], array);
}
}
} else if (root.isFile()) {
array.add(readFile(root));
}
}
}
参数
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static JSONObject readFile(File file) {
JSONObject json = new JSONObject();
json.put("fileName", file.getName());
json.put("filePath", file.getPath().replaceAll("\\\\", "/"));
json.put("size", Util.fileSizeFormat(file.length()));
json.put("extname", getFileExtension(file));
json.put("fileFlag", "f");
json.put("updateTime", formatter.format(file.lastModified()));
return json;
}
private static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return "";
}
public static String fileSizeFormat(long length) {
DecimalFormat df = new DecimalFormat("#0.0");
float size = (float) length / 1024;
String sumFilesize = "";
if (size >= 0 && size < 1) {
sumFilesize = length + "B";
} else if (size >= 1 && size < 1024) {
sumFilesize = df.format(size) + "K";
} else if (size >= 1024) {
size = size / 1024;
if (size >= 1 && size < 1024) {
sumFilesize = df.format(size) + "M";
} else if (size >= 1024) {
size = size / 1024;
sumFilesize = df.format(size) + "G";
}
}
return sumFilesize;
}
}
serviceImpl
JSONArray array = new JSONArray();
File file = new File(folderpath);
ReadFile.readCurrentAllFile(file,array);
JSONArray array1 = JSONArray.fromObject(array.stream().filter(distinctByKey(item -> ((JSONObject) item).getString("filePath"))).collect(Collectors.toList()));