打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

2022.12.02 湖南

关注

七八月的天空

于 2018-12-16 12:01:44 发布

5283

 收藏 4

分类专栏: 前端

版权

前端

专栏收录该内容

32 篇文章0 订阅

订阅专栏

实现读取本地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>

效果图:

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

————————————————

版权声明:本文为CSDN博主「七八月的天空」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/x18094/article/details/85030115

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
巧用dimens适配多个分辨率(二) | 望月听涛
poi批量实现导入功能,jxl实现导入预览功能
java对本地日志文件的读写
Java操作文件、目录
文件夹操作及zip的子文件读取,解压-文件下载
Android上传文件到服务器
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服