StringBuilder buf=new StringBuilder();
public String fileToJsonByPath(String path) {
if(path.isEmpty()){
return null;
}
File f = new File(path);
if (f.isDirectory())
{
scanToJson(new File(path));
buf.delete(buf.length() - 2, buf.length());
}
else {
System.out.format("{\"name\" : \"%s\"}", f.getName());
}
return buf.append("}").toString();
}
public void scanToJson(File f) {
if (f.isDirectory())
{
buf.append("{").append("\"name\" : \"").append(f.getName()).append("\",").append("\"filePath\":\"\",").append("\"isDir\":\"0\",").append("\"children\":[");
Arrays.asList(f.listFiles()).forEach(this::scanToJson);
if(buf.toString().endsWith("\"children\":[")) {
buf.append("{\"name\":\"暂无文件\",\"path\":\"\",\"isDir\":\"0\"},");
}
buf.delete(buf.length() - 2, buf.length());
buf.append("}").append("]").append("},");
}
else {
buf.append("{").append("\"name\" : \"").append(f.getName()).append("\"").append(",\"filePath\":").append(JSON.toJSONString(f.getAbsolutePath())).append(",\"isDir\":\"1\"").append("},");
}
}
自己再把string转成json传给前端就行
返回的json串
{
"children": [
{
"children": [
{
"children": [
{
"filePath": "D:\\Download\\202201\\excel\\20220101——excel.txt",
"name": "20220101——excel.txt",
"isDir": "1"
}
],
"filePath": "",
"name": "excel",
"isDir": "0"
},
{
"children": [
{
"filePath": "D:\\Download\\202201\\pdf\\新建 Microsoft Excel 工作表.xlsx",
"name": "新建 Microsoft Excel 工作表.xlsx",
"isDir": "1"
}
],
"filePath": "",
"name": "pdf",
"isDir": "0"
}
],
"filePath": "",
"name": "202201",
"isDir": "0"
},
{
"children": [
{
"path": "",
"name": "暂无文件",
"isDir": "0"
}
],
"filePath": "",
"name": "202202",
"isDir": "0"
},
{
"children": [
{
"filePath": "D:\\Download\\aaa\\新建 文本文档.txt",
"name": "新建 文本文档.txt",
"isDir": "1"
}
],
"filePath": "",
"name": "aaa",
"isDir": "0"
},
{
"filePath": "D:\\Download\\ca.cer",
"name": "ca.cer",
"isDir": "1"
},
{
"children": [
{
"children": [
{
"path": "",
"name": "暂无文件",
"isDir": "0"
}
],
"filePath": "",
"name": "houhuiyao",
"isDir": "0"
}
],
"filePath": "",
"name": "DwnlData",
"isDir": "0"
},
{
"filePath": "D:\\Download\\exportAll1670495117699.xlsx",
"name": "exportAll1670495117699.xlsx",
"isDir": "1"
},
{
"filePath": "D:\\Download\\exportAll1670495147848.xlsx",
"name": "exportAll1670495147848.xlsx",
"isDir": "1"
},
{
"filePath": "D:\\Download\\exportAll1670495173838.xlsx",
"name": "exportAll1670495173838.xlsx",
"isDir": "1"
},
{
"filePath": "D:\\Download\\lanserverproperties-1.9.1-forge.jar",
"name": "lanserverproperties-1.9.1-forge.jar",
"isDir": "1"
},
{
"filePath": "D:\\Download\\ServerPropertiesLAN-2.65-1.7.10.jar",
"name": "ServerPropertiesLAN-2.65-1.7.10.jar",
"isDir": "1"
},
{
"filePath": "D:\\Download\\stdout",
"name": "stdout",
"isDir": "1"
},
{
"filePath": "D:\\Download\\stdout (1)",
"name": "stdout (1)",
"isDir": "1"
}
],
"filePath": "",
"name": "Download",
"isDir": "0"
}