gpt4 book ai didi

javascript - java中读取目录结构并将其转换为JSON对象

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:58 25 4
gpt4 key购买 nike

我需要读取文件系统中的目录结构并将其转换为java中的Json对象,以便在javascript中进一步处理。最合适的继续方式是什么?

最佳答案

我最近想出了一个解决方案,想与大家分享。假设我们知道层次结构的级别,下面是将给定文件结构转换为 JSON 对象的代码。

public static void convert_to_JSON(File node) {
File[] subnode = node.listFiles();
JSONArray ja_root = new JSONArray(); //the node has 2 different directories
JSONArray ja_pattern = new JSONArray();
JSONArray ja_library = new JSONArray();
JSONArray ja_category = new JSONArray();

for (File filename : subnode) {
if ("newfileroot".equals(filename.getName()) || "talendfileroot".equals(filename.getName())) { // String[] libraries;
File[] libraries = filename.listFiles();
for (File lib : libraries) {
File[] categories = lib.listFiles();


for (File cat : categories) {
if (cat.isDirectory()) {
File[] patterns = cat.listFiles();

for (File pat : patterns) {


if (pat.isDirectory()) {
ja_pattern.add(pat.getAbsoluteFile().getName());


}

}
//createjson object here - put cat as key and json array as value
JSONObject jo2 = new JSONObject();
jo2.put(cat.getAbsoluteFile().getName(), ja_pattern);
ja_category.add(jo2);
ja_pattern = new JSONArray();
}

}
JSONObject jo3 = new JSONObject();
jo3.put(lib.getAbsoluteFile().getName(), ja_category);
ja_library.add(jo3);
ja_category = new JSONArray();
}
JSONObject jo4 = new JSONObject();
jo4.put(filename.getAbsoluteFile().getName(), ja_library);
ja_root.add(jo4);

ja_library = new JSONArray();
}

}
JSONObject jo5 = new JSONObject();
jo5.put(node.getAbsoluteFile().getName(), ja_root);

try (FileWriter file = new FileWriter("d:\\file_structure.json")) {
file.write(jo5.toJSONString());
file.flush();
} catch (IOException e) {
}
}

}

关于javascript - java中读取目录结构并将其转换为JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44366518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com