七八月的天空 于 2018-12-16 12:01:44 發(fā)布 5283 收藏 4 分類專欄: 前端 版權(quán) 前端 專欄收錄該內(nèi)容 32 篇文章0 訂閱 訂閱專欄 實現(xiàn)讀取本地e盤下的一個學(xué)習(xí)目錄,通過樹形展現(xiàn)出來,并且點擊節(jié)點就可以打開文本內(nèi)容。 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內(nèi)容: <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(),//節(jié)點數(shù)據(jù) expanded: false,//初始是否展開 levels: 1,//初始顯示層數(shù) 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-同步(當(dāng)這個ajax執(zhí)行完后才會繼續(xù)執(zhí)行其他代碼);異步-與其他代碼互不影響,一起運行。 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-同步(當(dāng)這個ajax執(zhí)行完后才會繼續(xù)執(zhí)行其他代碼);異步-與其他代碼互不影響,一起運行。 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+"http://filltree.json"); if(f.exists()){ return FileUtil.fileToString(path+"http://filltree.json",null,"utf-8"); }else{ List<Map<String, Object>> list = new ArrayList<>(); String content = getTree(null, list); FileUtil.writeFile(path+"http://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 * 寫入內(nèi)容 * @param needRename * 是否需要重命名 */ public static void writeFile(String filePath, String content, boolean needRename) { String realPath = null; if (needRename) { realPath = rename(filePath); } else { realPath = filePath; } // FileOutputStream會出現(xiàn)中文亂碼,用 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會出現(xiàn)中文亂碼,用 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 替換文件中的內(nèi)容 * @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關(guān)閉之后 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關(guān)閉之后 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:///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> 效果圖: 點擊左邊節(jié)點(非目錄文件),文本內(nèi)容顯示在右邊。 ———————————————— 版權(quán)聲明:本文為CSDN博主「七八月的天空」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/x18094/article/details/85030115 |
|