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”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM