递归读取制定目录下所有文件夹和文件的实现(java)

时间:2022-09-24 12:27:13
  public static String getAllDirectorisAndFiles(String path){
    	Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("time_stamp", Tools.currentTime());
		String responseString = "";
		try {
			getDirectorisAndFiles(path, responseMap, "data");
			responseString = (new Gson()).toJson(responseMap);
		} catch (Exception e) {
			System.out.println("files列表读取异常");
		}
		return responseString;
    }
    
    public static void getDirectorisAndFiles(String path, Map<String, Object> resultMap, String directoryName) {
    	System.out.println(path);
    	System.out.println(directoryName);
    	File file = new File(path);
    	ArrayList<Object> dataArray = new ArrayList<Object>();
        File [] files = file.listFiles();
        
        for(File a:files)
        {
            if(a.isDirectory())
            {
            	Map<String, Object> tempMap = new HashMap<String, Object>();
            	getDirectorisAndFiles(path + a.getName() + "/", tempMap, a.getName());
            	dataArray.add(tempMap);
            }else{
            	dataArray.add(a.getName());
            }
        }
        resultMap.put(directoryName, dataArray);
	}