JAVA 获取某个盘符下所有文件夹及其文件路径,并返回标准JSON字符串
本文借鉴网络上的写法,由于仓促忘记了打开的是哪个网页,希望不要介意。
拿过来代码,发现逻辑虽然通,但由于json字符串拼装错误,导致返回的字符串并不正确,所以拿来优化了一下:
import com.alibaba.fastjson.JSON;
import com.googosoft.util.Validate;
import java.io.File;
import java.util.Arrays;
public class DirectoryUtils {
StringBuilder buf=new StringBuilder();
public String scan(String path) {
if(Validate.isNull(path)){
return null;
}
File f = new File(path);
if (f.isDirectory())
{
scan(new File(path));
buf.delete(buf.length() - 2, buf.length());
}
else {
System.out.format("{\"name\" : \"%s\"}", f.getName());
}
return buf.toString();
}
private void scan(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::scan);
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("},");
}
}
{
"name": "fileupload",
"children": [
{
"name": "文件夹A",
"children": [
{
"name": "0001",
"children": [
{
"name": "2017-09-29",
"children": [
{
"name": "crash-2017-09-29-1506665339302.log",
"path": "D: \\IdeaTomcat\\apache-tomcat-7.0.43-PB\\fileupload\\文件夹A\\0001\\2017-09-29\\crash-2017-09-29-1506665339302.log" }
]
}
]
}
]
},
{
"name": "文件夹B",
"children": [
{
"name": "0001",
"children": [
{
"name": "2017-09-29",
"children": []
}
]
}
]
}
]
}
如果结合LayUi tree,对象类是这样的
public class Directory {
private String name;//文件夹名
private List<String> children;//子文件夹
private String path;//文件路径
private String isDir;//是否是文件夹
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getChildren() {
return children;
}
public void setChildren(List<String> children) {
this.children = children;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getIsDir() {
return isDir;
}
public void setIsDir(String isDir) {
this.isDir = isDir;
}
}
DirectoryUtils dir =new DirectoryUtils();
String json=dir.scan(rootPath)+"}";
if (Validate.noNull(json)) {
direct = JSON.parseObject(json, Directory.class);
}
mv.addObject("Directory", direct);
前台在需要的地方,只需要引用这样一句话就OK
${Directory.children}
效果图