bootstrap-treeview demo (树形展示与后台数据交互)

实现读取本地e盘下的一个学习目录,通过树形展现出来,并且点击节点就可以打开文本内容。

html 引入:

   <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap-treeview.min.css" />
    <script type="text/javascript" src="../skeleton/jquery-3.3.1.js"></script>
    <!--<script type="text/javascript" src="../plugins/bootstrap/js/bootstrap.js" ></script>-->
    <script type="text/javascript" src="../plugins/bootstrap/js/bootstrap-treeview.min.js" ></script>
    <style type="text/css">
        .list-group-item {
            position: relative;
            display: block;
            padding: 0;
            margin-bottom: -1px;
            background-color: #fff;
            border: 1px solid #ddd;
        }
    </style>

 body内容:

<div style=" overflow:scroll; width:20%; height:620px;float:left">
    <div id="tree"></div>
</div>
<div style=" overflow:scroll; width:80%; height:620px;float:left">
    <div id="content" style="width:80%;float:left;border: solid #f7f7f9;">
    </div>
</div>

脚本: 

<script type="text/javascript">
    $(function () {
        $('#tree').treeview({
            data: getTree(),//节点数据
            expanded: false,//初始是否展开
            levels: 1,//初始显示层数
            icon: "glyphicon glyphicon-stop",
            selectedIcon: "glyphicon glyphicon-stop",
            color: "#000000",
            backColor: "#FFFFFF",
            onNodeSelected: function (event, data) {
                console.log("you are choose me now :" + data.id);
                openFile(data.id);
            }
        });
    });

    function openFile(path) {
        $.ajax({
            url: "/tree/open",
            type: "post",
            contentType: "application/json",
            timeout: 30000, //超时时间:30秒
            async: false,//false-同步(当这个ajax执行完后才会继续执行其他代码);异步-与其他代码互不影响,一起运行。
            dataType: "text",
            data: path,
            success: function (data) {
                console.log("succes" + data);
                $("#content").html(data);
                /*  $("#content").val(data);
                  $("#content").append(data);*/
            }, error: function (data) {
                console.log("error");
            }
        });
    }

    function getTree() {
        var tree = {};
        $.ajax({
            url: "/tree/query2",
            type: "post",
            contentType: "application/json",
            timeout: 30000, //超时时间:30秒
            async: false,//false-同步(当这个ajax执行完后才会继续执行其他代码);异步-与其他代码互不影响,一起运行。
            dataType: "json",
            success: function (data) {
                // console.log(data);
                tree = data;
            }, error: function (data) {
                console.log(data);
            }
        });
        return tree;
    }
</script>

后台:

import com.alibaba.fastjson.JSONArray;
import com.tools.FileUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tree")
public class TreeController {

    /**
     * @param path
     * @param list
     * @return
     */
    @RequestMapping("/query")
    public static String getTree(String path, List<Map<String, Object>> list) {
        String newPath = " ";
        if (path == null) {
            path = "E:\\工具资料";
        }
        Object[] objs = FileUtil.getFileAndFolders(path);
        for (Object s : objs) {
            if (String.valueOf(s).indexOf(".") == -1) {//如果是目录
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", path+"\\"+s);
                map.put("text", s);
                newPath = path.concat("\\").concat(s.toString());
                if (FileUtil.isDirectory(newPath)) {//如果是目录,往下搜索
                    List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
                    map.put("nodes", childList);
                    getTree(newPath, childList);
                }
                list.add(map);
            } else {//如果是文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", path+"\\"+s);
                map.put("text", s);
                list.add(map);
            }
        }

        return JSONArray.toJSONString(list);
    }

    @RequestMapping("/query2")
    public String queryTree() {
        String path = System.getProperty("user.dir");
        File f = new File(path+"//filltree.json");
        if(f.exists()){
           return  FileUtil.fileToString(path+"//filltree.json",null,"utf-8");
        }else{
            List<Map<String, Object>> list = new ArrayList<>();
            String content = getTree(null, list);
            FileUtil.writeFile(path+"//filltree.json", content,false);
            return content;
        }
    }
    @RequestMapping("/open")
    public String openFile(@RequestBody String path){
        File f = new File(path);
            if(f.isFile()){
                return FileUtil.fileToString(path,"<br>",FileUtil.getFileCharset(path));
            }
            return "";
    }
}

 工具类:

package com.tools;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;


public class FileUtil {
	private static final String CODE_ING = "utf-8";

	/*
	 * File - FileReader FileInputStream --InputstreamReader-- BufferedReader
	 * 
	 */
	/**
	 * 
	 * @desc FileOutputStream写文件
	 * @date 2017年9月18日
	 * @author 
	 * @param filePath
	 *            文件路径
	 * @param content
	 *            写入内容
	 * @param needRename
	 *            是否需要重命名
	 */
	public static void writeFile(String filePath, String content, boolean needRename) {
		String realPath = null;
		if (needRename) {
			realPath = rename(filePath);
		} else {
			realPath = filePath;
		}
		// FileOutputStream会出现中文乱码,用 OutputStreamWriter
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(realPath), "utf-8");
			osw.write(content);
			osw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void writeFile(File file, String content) {
		// FileOutputStream会出现中文乱码,用 OutputStreamWriter
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
			osw.write(content);
			osw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @describe 替换文件中的内容
	 * @author 
	 * @date 2017年10月11日
	 * @param filePath
	 * @param oldStr
	 * @param newStr
	 */
	public static int replaceContent(String filePath, String oldStr, String newStr) {
		int cnt = 0;
		File file = new File(filePath);
		BufferedReader buf = null;
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), CODE_ING));
		} catch (UnsupportedEncodingException | FileNotFoundException e) {
			e.printStackTrace();
		}
		File tmpFile = new File(filePath + ".tmp");
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile));
			String str1 = "";
			boolean isNeed = false;
			while ((str1 = buf.readLine()) != null) {
				if (str1.contains(oldStr)) {
					isNeed = true;
					bw.write(str1.replace(oldStr, newStr) + "\r\n");
					cnt++;
				} else {
					bw.write(str1 + "\r\n");
				}
			}
			buf.close();
			if (bw != null) {
				bw.close();
			}
			// 重命名一定要写在bw关闭之后
			if (isNeed) {
				file.delete();
				tmpFile.renameTo(new File(filePath));
			} else {
				tmpFile.delete();
			}

		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return cnt;
	}

	public static int replaceArrayList(String filePath, String oldStr) {
		int cnt = 0;
		File file = new File(filePath);
		BufferedReader buf = null;
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), CODE_ING));
		} catch (UnsupportedEncodingException | FileNotFoundException e) {
			e.printStackTrace();
		}
		File tmpFile = new File(filePath + ".tmp");
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile));
			String str1 = "";
			boolean isNeed = false;
			String headStr = "";
			String tmp = "";
			while ((str1 = buf.readLine()) != null) {
				if (str1.contains(oldStr)) {
					isNeed = true;
					headStr = str1.split("=")[0];
					tmp = headStr.substring(headStr.indexOf("List<") + 5, headStr.lastIndexOf(">"));
					bw.write(str1.replace(oldStr, "ArrayList<" + tmp + ">") + "\r\n");
					cnt++;
				} else {
					bw.write(str1 + "\r\n");
				}
			}
			buf.close();
			if (bw != null) {
				bw.close();
			}
			// 重命名一定要写在bw关闭之后
			if (isNeed) {
				file.delete();
				tmpFile.renameTo(new File(filePath));
			} else {
				tmpFile.delete();
			}

		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return cnt;
	}

	/**
	 * 
	 * @describ
	 * @author 
	 * @date 2017年10月27日
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static List<String> fileToList(String file, String charSet) {
		List<String> list = new ArrayList<>();
		BufferedReader buf = null;
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
			String str = null;
			while ((str = buf.readLine()) != null) {
				StringBuffer sb = new StringBuffer();
				sb.append(str);
				//sb.append(SystemUtil.isWin() ? "\r\n" : "\n");
				list.add(sb.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		String tmp = list.get(list.size() - 1);
		list.remove(list.size() - 1);
	//	list.add(StrUtil.trunc(tmp, SystemUtil.isWin() ? "\r\n" : "\n"));
		return list;
	}

	public static String fileToString(String file,String addRow, String charSet) {
		BufferedReader buf = null;
		String str = null;
		StringBuffer sb = new StringBuffer();
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));

			while ((str = buf.readLine()) != null) {
				sb.append(str);
				if(addRow!=null)
				sb.append(addRow);
			}
			buf.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (buf != null) {
				try {
					buf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String result = sb.toString();
		// return result.substring(0, result.lastIndexOf("\r\n"));
		return result;
	}
	public static String fileToStringOri(String file, String charSet) {
		BufferedReader buf = null;
		String str = null;
		StringBuffer sb = new StringBuffer();
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
			
			while ((str = buf.readLine()) != null) {
				sb.append(str);
				//sb.append("\r\n");
			}
			buf.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (buf != null) {
				try {
					buf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String result = sb.toString();
		// return result.substring(0, result.lastIndexOf("\r\n"));
		return result;
	}

	/**
	 * 
	 * @desc 如果有文件夹下同名文件重命名(2)
	 * @date 2017年9月18日
	 * @author S
	 * @param filePath
	 * @return
	 */
	public static String rename(String filePath) {
		// 获取文件名的方式
		// 方式一:
		// String fileName=path.substring(path.lastIndexOf("/")+1);
		File file = new File(filePath);
		// 方式二:
		String fileName = file.getName();
		int index = fileName.indexOf(".");
		File fileDir = new File(filePath.substring(0, filePath.lastIndexOf(fileName)));
		String[] files = fileDir.list();
		int max = 0, tmp = 0;
		StringBuffer sb = new StringBuffer();
		// 寻找同名文件
		boolean isNeed = false;
		for (String string : files) {
			if (!string.contains(fileName.substring(0, index))) {
				continue;
			}
			isNeed = true;
			if (string.indexOf("(") != -1 && string.indexOf(")") != -1) {
				if (!string.substring(0, string.indexOf("(")).equals(fileName.substring(0, index))) {
					continue;
				}
				tmp = Integer.parseInt(string.substring(string.indexOf("(") + 1, string.indexOf(")")));
				max = max < tmp ? tmp : max;
			}
		}
		if (!isNeed)
			return filePath;
		sb.append(filePath.substring(0, filePath.indexOf(fileName)));
		sb.append(fileName.substring(0, index));
		sb.append("(");
		sb.append(max + 1);
		sb.append(")");
		sb.append(fileName.substring(index));
		return sb.toString();
	}

	/**
	 * 
	 * @describe 取出文件夹下的所有文件名目录名
	 * @author Snake^_^
	 * @date 2017年10月10日
	 * @param folderPath
	 * @return
	 */
	public static String[] getFileAndFolders(String folderPath) {
		File fileDir = new File(folderPath);
		return fileDir.list();
	}
	public static File[] getFiles(String folderPath) {
		File fileDir = new File(folderPath);
		return fileDir.listFiles();
	}

	public static void find(String rootPath, String targetStr) {
		File file = new File(rootPath);
		File[] files = file.listFiles();
		for (File file2 : files) {
			boolean flag = false;
			if (file2.isFile()) {
				BufferedReader buf = null;
				try {
					buf = new BufferedReader(new InputStreamReader(new FileInputStream(file2), CODE_ING));
				} catch (UnsupportedEncodingException | FileNotFoundException e) {
					e.printStackTrace();
				}
				String str = null;
				try {
					while ((str = buf.readLine()) != null) {
						if (str.contains(targetStr)) {
							flag = true;
							break;
						}
					}
					buf.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (buf != null) {
						try {
							buf.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			} else if (file2.getName().contains(targetStr)) {
				flag = true;
			}
			if (flag) {
				System.out.println(file2.getAbsolutePath());
			}
		}
	}

	/**
	 * 
	 * @describe
	 * @author S
	 * @date 2017年10月27日
	 * @param rootPath
	 * @param targetFile
	 */
	public static List<String> findAllSameFile(String rootPath, String targetFile, List<String> list) {
		File file = new File(rootPath);
		File[] files = file.listFiles();
		if (list == null) {
			list = new ArrayList<>();
		}
		for (File file2 : files) {
			if (file2.isDirectory()) {
				System.out.println(1);
				findAllSameFile(file2.getAbsolutePath(), targetFile, list);
			} else if (file2.isFile() && file2.getName().equals(targetFile)) {
				System.out.println(2);
				list.add(file2.getAbsolutePath());
			}
		}
		return list;
	}

	/**
	 * 
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String inputStreamToString(InputStream in, String charset) throws IOException {
		BufferedReader buf = new BufferedReader(new InputStreamReader(in, charset));
		StringBuffer sb = new StringBuffer();
		String str = null;

		while ((str = buf.readLine()) != null) {
			sb.append(str);
			sb.append("\r\n");
		}
		buf.close();

		return sb.toString();
	}

	/**
	 * 
	 * @describe 判断是否文件夹
	 * @date 2018-05-08
	 * @param path
	 * @return
	 */
	public static boolean isDirectory(String path) {
		File file = new File(path);
		return file.isDirectory();
	}

	public static boolean isFile(String path) {
		File file = new File(path);
		return file.isFile();
	}

	/**
	 * 判断文件的编码格式
	 * 
	 * @param fileName
	 *            :file
	 * @return 文件编码格式
	 * @throws Exception
	 */
	public static String codeString(String fileName) {
		BufferedInputStream bin;
		String code = null;
		try {
			bin = new BufferedInputStream(new FileInputStream(fileName));
			int p = (bin.read() << 8) + bin.read();

			switch (p) {
			case 0xefbb:
				code = "UTF-8";
				break;
			case 0xfffe:
				code = "Unicode";
				break;
			case 0xfeff:
				code = "UTF-16BE";
				break;
			default:
				code = "GBK";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return code;
	}

	private static void judgeTxtCode(String path) throws Exception {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(path);
			int a = fis.read();
			int b = fis.read();
			if (a == 0xFF && b == 0xFE) {
				System.out.println("Unicode");
			} else if (a == 0xFE && b == 0xFF) {
				System.out.println("UTF-16BE");
			} else if (a == 0xEF && b == 0xBB) {
				System.out.println("UTF-8");
			} else {
				System.out.println("GBK");
			}
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}

	public static String getFileCharset(String filePath) {
		// 通过文件路径来获得文件
		File file = new File(filePath);

		Charset charset = null;
		try {
			// 获取原始文件编码
			CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
			detector.add(JChardetFacade.getInstance());
			charset = detector.detectCodepage(file.toURL());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return charset.name().equalsIgnoreCase("utf-8")?"utf-8":"gbk";
	}

}

 pom所需依赖:

  <!-- 判断文件编码 https://mvnrepository.com/artifact/cpdetector/cpdetector -->
<!--mylib是我本地的目录,自己去下载就好了-->
        <dependency>
            <groupId>mylib.cpdetector</groupId>
            <artifactId>chardet</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>mylib</groupId>
            <artifactId>cpdetector</artifactId>
            <version>1.0.10</version>
        </dependency>

效果图:

点击左边节点(非目录文件),文本内容显示在右边。 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值