fighter66
我绝不秃头
采纳率16.7%
2018-04-16 09:52

遍历文件夹,显示列表

20
  • 遍历
  • 结构
  • web
已采纳

求助帮忙写个遍历文件夹,并在web页面上以树状结构显示文件列表,
可以的话每个文件加个点击事件显示文件路径

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

8条回答

  • ApatheCrazyFan ApacheCrazyFan 3年前

    做的不是很好:

    页面:

    <!DOCTYPE html>
    <html lang="zh_CN">
    <head>
        <meta charset="UTF-8">
        <title>文件目录</title>
        <link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" />
        <!--使用zTree风格-->
        <link rel="stylesheet" href="static/custom/fileCatalog/css/metroStyle/metroStyle.css" />
    
        <script type="text/javascript" src="static/jquery/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="static/bootstrap/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="static/custom/fileCatalog/js/jquery.ztree.all.min.js"></script>
        <script type="text/javascript" src="static/custom/fileCatalog/fileCatalog.js"></script>
    </head>
    <body>
    <div>
        <!-- Nav tabs -->
        <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
        </ul>
        <!-- Tab panes -->
        <div class="tab-content">
            <div role="tabpanel" class="tab-pane active" id="home">
                <ul class="ztree" id="menu"></ul>
            </div>
        </div>
    </div>
    </body>
    </html>
    

    js:

     /**
     * Created by wangbiao-019 on 2018/4/17.
     */
    var setting = {
        view: {
            //addHoverDom: addHoverDom,
            //removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: false
        },
        callback: {
            onClick: zTreeOnClick
        }
    };
    
    var zNodes;
    $.ajax({
        url:"fileCatalog/fileCatalogs",
        type:"GET",
        dataType:"json",
        success:function (data) {
            zNodes = data;
            //console.info(zNodes);
        },
        error:function (error) {
            console.info(error);
        }
    });
    
    function concatParentsPath(currNode){
        if(currNode.getParentNode() == null){
            return currNode.name;
        }else{
            return concatParentsPath(currNode.getParentNode() ) + currNode.name;
        }
    
    }
    
    function zTreeOnClick(e, treeId, treeNode){
        var nodes = $.fn.zTree.getZTreeObj(treeId).getSelectedNodes();
        var namePath = concatParentsPath(nodes[0]);
        $("#namePath").text(namePath);
    }
    
    function initZTree(id){
        $.fn.zTree.init($(id), setting, zNodes);
    }
    
    $(document).ready(function () {
        initZTree("#menu");
    });
        //{ id: 1, pId: 0, name: "父节点1", open: true },
    
    

    Controller:

     package com.example.demo.on.controller;
    
    import com.example.demo.common.entity.Ztree;
    import com.example.demo.common.util.FileCatalogUtil;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by wangbiao-019 on 2018/4/17.
     */
    @Controller
    @RequestMapping("/fileCatalog")
    public class FileCatalogController {
        private List<Ztree.Node> nodes;
    
    
        @GetMapping("/fileCatalogs")
        @ResponseBody
        public List<Ztree.Node> getFileCatalogs() {
            nodes = new ArrayList<Ztree.Node>();
    
            Ztree ztree = FileCatalogUtil.ergodicDeeply("D:/GitRespository/ideag/myspecial/src/main/java/com");
    
            Ztree.Node root = ztree.getRoot();
    
            mObj2Json(root);
    
            System.out.println( nodes);
    
            return nodes;
        }
    
        private void mObj2Json(Ztree.Node node){
            nodes.add(node);
    
            recur(node);
        }
        private void recur(Ztree.Node node){
            if(node != null && node.getSons() != null && node.getSons().size() > 0) {
                for (Ztree.Node n : node.getSons()) {
                    nodes.add(n);
                    recur(n);
                }
            }
        }
    
    }
    
    

    model:

     package com.example.demo.common.entity;
    
    import java.util.List;
    
    /**
     * Created by wangbiao-019 on 2018/4/17.
     */
    public class Ztree {
    
        public class Node{
            int id;
            int pId;
            String name;
            boolean open;   //是否展开
            boolean isParent;   //是否是父节点
            int fileCount;
            List<Node> sons;
    
            public Node(){
                this.open = false;
                this.isParent = false;
            }
    
            public int getId() {
                return id;
            }
    
            public void setId(int id) {
                this.id = id;
            }
    
            public int getpId() {
                return pId;
            }
    
            public void setpId(int pId) {
                this.pId = pId;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public boolean isOpen() {
                return open;
            }
    
            public void setOpen(boolean open) {
                this.open = open;
            }
    
            public boolean isParent() {
                return isParent;
            }
    
            public void setParent(boolean parent) {
                isParent = parent;
            }
    
            public int getFileCount() {
                return fileCount;
            }
    
            public void setFileCount(int fileCount) {
                this.fileCount = fileCount;
            }
    
            public List<Node> getSons() {
                return sons;
            }
    
            public void setSons(List<Node> sons) {
                this.sons = sons;
            }
    
            @Override
            public String toString() {
                return "{" +
                        "\"id\":\"" + id +
                        "\", \"pId\":\"" + pId +
                        "\", \"name\":\"" + name +
                        "\", \"open\":\"" + open +
                        "\", \"isParent\":\"" + isParent +
                        "\"}";
            }
        }
        Node root;
    
        public Node getRoot() {
            return root;
        }
        public void setRoot(Node root) {
            this.root = root;
        }
    
        //
    }
    
    

    util:
    package com.example.demo.common.util;

    import com.example.demo.common.entity.Ztree;
    import com.example.demo.common.entity.Ztree.Node;

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    /**

    • Created by wangbiao-019 on 2018/4/17.
      */
      public class FileCatalogUtil {
      private static int INT_START = 1;
      private static final int INT_PARENT = 0;

      public static Ztree ergodicDeeply(String path) {
      return ergodic(path, -1);
      }

      //遍历文件夹的任意深度
      // -1 表示会遍历到底,直至爆炸
      // >0 表示遍历文件夹下的n层
      // <0 return null;
      public static Ztree ergodic(String path, int deepty) {
      if (path == null || "".equals(path.trim()) || deepty == 0) {
      return null;
      } else {
      Ztree ztree = new Ztree();
      ztree.setRoot(nodefor(new File(path), ztree, deepty, INT_PARENT));
      return ztree;
      }
      }

      private static Ztree.Node nodefor(File file, Ztree ztree, int deepth, int parentId) {
      List nodes;
      Node node;
      if (file == null) {
      return null;
      } else if (deepth == 0) {
      return null;
      } else if (deepth == -1) {
      if (file.exists()) {
      node = ztree.new Node();

              node.setId(INT_START);
              node.setpId(parentId);
              try {
                  if (file.isDirectory()) { //是目录
                      String path = null;
                      path = file.getCanonicalPath();
      
                      node.setName(parentId == 0 ? path : path.substring(path.lastIndexOf(File.separator)));
                      node.setParent(true);
      
                      String[] fs = file.list();
                      if (fs == null) {
                          return node;
                      } else {
                          nodes = new ArrayList<Node>();
                          for (String s : fs) {
                              File fi = new File(file.getCanonicalPath(), s);
                              INT_START++;
                              nodes.add(nodefor(fi, ztree, deepth, node.getId()));
                          }
                          node.setSons(nodes);
                      }
                  } else if (file.isFile()) { //是文件
                      node.setName(file.getName());
                      INT_START++;
                  } else if (file.isHidden()) { //是隐藏
                      node.setName(file.getName());
                      INT_START++;
                  } else {  //其他
                      node.setName(file.getName());
                      INT_START++;
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          } else {
              return null;
          }
      } else if (deepth > 0) {
          return null;
      } else {
          return null;
      }
      return node;
      

      }

    }

    点赞 评论 复制链接分享
  • beachwhb 仔仔love 3年前

    不能遍历本地文件夹,只能遍历服务器的文件夹,因为代码是放在服务器的,客户用浏览器去请求服务器代码,服务器代码运行后把结果返回到你的浏览器。

    点赞 1 评论 复制链接分享
  • ApatheCrazyFan ApacheCrazyFan 3年前

    效果展示:
    图片说明

    不足,1.当目录结构复杂,文件多的时候需要创建很多的 Ztree的Node对象。
    2. 上面的 nodefor方法在 deepth > 0 的情况下没有写,请那个啥

    点赞 评论 复制链接分享
  • zsy61314 LoseAnson洛施安森 3年前

    遍历文件 形成一个树 每个页面展示列表

    点赞 评论 复制链接分享
  • qq_34209997 子麟 3年前

    需要用哪种语言写,你要遍历哪的文件,服务器上的还是本地的

    点赞 评论 复制链接分享
  • qq_37543050 qq_37543050 3年前

    看看改一下
    package management;

    import java.io.File;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.List;
    import java.text.ParseException;
    import java.util.Date;

    public class bro_logfile {

        /**
         * 
         * @author zdz8207
         */
    
    
        public List<String> getFileName() {
            String path = "/usr/local/bro/logs"; // 路径
            File f = new File(path);
            List<String> list =new ArrayList<String>();
            if (!f.exists()) {
                list.add(path + " not exists");
    
            }
    
            File fa[] = f.listFiles();
            for (int i = 0; i < fa.length; i++) {
                File fs = fa[i];
                if (fs.isDirectory()) {
                    list.add(fs.getName() + " [文件夹]");
                } else {
                    list.add(fs.getName());
                }
            }
            return list;
        }
    
    
    
        public String  remove(String start, String end) throws ParseException, InterruptedException, IOException{
             try {  
                 Calendar c = Calendar.getInstance();
                 DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
    
                 //开始时间必须小于结束时间
    
                 Date beginDate =dateFormat1.parse(start);
                 Date endDate =  dateFormat1.parse(end);
                 Date date = beginDate;
                 while (date.getTime() <= endDate.getTime()) {
                 String date1=dateFormat1.format(date);
                 c.setTime(date);
                 c.add(Calendar.DATE, 1); // 日期加1天
                 date = c.getTime();
                 String cmd="rm -rf "+"/usr/local/bro/logs/"+date1;
                 System.out.println(cmd);
                 Runtime.getRuntime().exec(cmd); 
               }
    
             } catch (IOException e) {  
                 e.printStackTrace();  
             }  
    
             String result="删除成功!";
                return result;
         }
    
    
    
        public static void main(String[] args) throws ParseException, InterruptedException, IOException {
            //remove("2017-04-02","2017-04-05");
            bro_logfile cs =new bro_logfile();
            String list=cs.remove("2017-06-04","2017-06-06");
    
            System.out.println(list);
        }
      }
    
    点赞 评论 复制链接分享
  • u013810758 longzl123 3年前

    ckfinder你值得拥有

    点赞 评论 复制链接分享
  • m0_37876214 m0_37876214 3年前

    是要用java还是php写呢

    点赞 评论 复制链接分享

为你推荐