package cn.neuq.hcg.everyday;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class PathToTreeUtil {
public static String getType(String filename, String path) {
if (path.endsWith(filename)) {
return "file";
}
return "folder";
}
public static void addPath(HashMap<String, Object> root, String path) {
String url = "";
String[] pathArr = path.split("/");
for (String name : pathArr) {
url += "/" + name;
boolean flag = true;
for (HashMap<String, Object> node : (ArrayList<HashMap<String, Object>>) root.get("content")) {
if (node.get("name").equals(name)) {
root = node;
flag = false;
break;
}
}
if (flag) {
HashMap<String, Object> new_node = new HashMap<>();
new_node.put("name", name);
new_node.put("type", getType(name, path));
new_node.put("url", url);
new_node.put("content", new ArrayList<HashMap<String, Object>>());
((ArrayList<HashMap<String, Object>>) root.get("content")).add(new_node);
root = new_node;
}
}
}
public static HashMap<String, Object> generate_data(String s) {
String[] paths = s.split(",");
HashMap<String, Object> root = new HashMap<>();
root.put("name", "");
root.put("url", "");
root.put("type", "");
ArrayList<String> arrayList = new ArrayList<>();
root.put("content", arrayList);
for (String path : paths) {
addPath(root, path);
}
return root;
}
public static String readFile(String pathname) throws Exception {
String str = "";
File file = new File(pathname);
try {
FileInputStream in = new FileInputStream(file);
int size = in.available();
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
str = new String(buffer, "GB2312");
} catch (IOException e) {
return null;
}
return str;
}
public static JSONObject pathToTree(String path) {
path = zhuanYi(path);
HashMap<String, Object> root = new HashMap<>();
root = generate_data(path);
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", root);
return jsonObject;
}
public static String zhuanYi(String path) {
System.out.println(path);
path = path.replaceAll("\"", "").replaceAll(" ", "");
if (path.contains("\\\\")) {
path = path.replaceAll("\\\\", "/");
System.out.println("把\\\\转成/");
System.out.println(path);
}
if (path.contains("//")) {
path = path.replaceAll("//", "/");
System.out.println