• java通过文件路径读取该路径下的所有文件并将其放入list中


    java通过文件路径读取该路径下的所有文件并将其放入list中

     
    java中可以通过递归的方式获取指定路径下的所有文件并将其放入List集合中。

    假设指定路径为path,目标集合为fileList,遍历指定路径下的所有文件,如果是目录文件则递归调用,如果是普通文件则放入fileList中。
    根据这个思路,得到java源代码如下所示:
    //方法getFiles根据指定路径获取所有的文件
    public ArrayList<File> getFiles(String path) throws Exception {
      //目标集合fileList
      ArrayList<File> fileList = new ArrayList<File>();
      File file = new File(path);
      if(file.isDirectory()){
        File []files = file.listFiles();
        for(File fileIndex:files){
          //如果这个文件是目录,则进行递归搜索
     if(fileIndex.isDirectory()){
       getFiles(fileIndex.getPath());
     }else {
          //如果文件是普通文件,则将文件句柄放入集合中
       fileList.add(fileIndex);
     }
        }
    }
      return fileList;
    }

    获取文件名:
    fileList = getFiles(this.getMenuPath());
    ArrayList<String> iconNameList = new ArrayList<String>();//返回文件名数组
    for(int i=0;i<fileList.size();i++){
        String curpath = fileList.get(i).getPath();//获取文件路径
        iconNameList.add(curpath.substring(curpath.lastIndexOf("\")+1));//将文件名加入数组
    }
    其中,在action中声明变量menuPath,并生成get和set方法:
      private String menuPath = "/resources/menuIcon";
    则this.getMenuPath()可以获取该路径,传入getFiles()方法时,该路径变为访问的绝对路径,例如“D:\tomcat\...\resources\menuIcon”

  • 相关阅读:
    C#中的语言记忆功能
    C#中 文件的打开及保存
    无边框窗体设置
    Windows获取浏览器中存储的明文密码
    (CVE-2020-17530)Struts2 S2-061漏洞复现
    (CVE-2020-14882​&14883)Weblogic RCE复现
    内网渗透学习-信息收集篇
    Spring Boot Actuator H2 RCE复现
    Linux解压文件
    Windows本地提权
  • 原文地址:https://www.cnblogs.com/limeiky/p/6229055.html
Copyright © 2020-2023  润新知