你的位置:首页 > Java教程

[Java教程][javaSE] java获取文件列表


递归测试

import java.io.File;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class FilesDemo {  private static final String FILE_PATH = "./";  private static List<Map<String, String>> FileList;  public static void main(String[] args) {    listFiles(new File(FILE_PATH), 1);    // for(Map<String,String> item:FileList){    // System.out.println("{name:"+item.get("name")+",level:"+item.get("level")+"}");    // }  }  public static void listFiles(File file, int level) {    FileList = new ArrayList<>();    Map<String, String> item;    File[] files = file.listFiles();    if (file.list().length != 0) {      for (File fileTemp : files) {        String fileName = fileTemp.getName();        System.out.println(getLevelPrefix(level) + fileName);        if (fileTemp.isDirectory() && fileTemp.list().length > 0) {          listFiles(fileTemp, level + 1);        } else {          item = new HashMap<String, String>();          item.put("name", fileTemp.getName());          item.put("level", String.valueOf(level));          FileList.add(item);        }      }    } else {      System.out.println(getLevelPrefix(level) + file.getName());    }  }  public static String getLevelPrefix(int level) {    StringBuilder sb = new StringBuilder();    for (int i = 1; i < level; i++) {      sb.append("  ");    }    sb.append("|--");    return sb.toString();  }}