Java递归读取文件夹下所有文档

/**
 * 递归读取文件夹下所有文档
 * @author Administrator
 *
 */
public class FileLoop{
    private static List<File> fileList = new ArrayList<File>();
    
    public static void main(String[] args) {
        List<File> list = fileReadLoop("c:/dir");
        
        for(int i=0; i<list.size(); i++){
             System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(list.get(i).lastModified()))+":"+list.get(i).getName());
         }
    }
    
     /**
      * 循环获取指定文件夹下的所有文件
      * @param path
      */
     private void loopReadDir(String path){
         File filePath = new File(path);
         File[] list = filePath.listFiles();
         if(list!=null && list.length>0){
             for(int i=0; i<list.length; i++){
                 File f = list[i];
                 if(f.isFile() && !f.isHidden()){
                     fileList.add(f);
                 }else if(f.isDirectory() && !f.isHidden()){
                     loopReadDir(f.getPath());
                 }
             }
         }
     }
     
     /**
      * 将文件按日期排序
      * @param list
      * @return
      */
     private void sortFileList(){
        //按文件日期排序
         Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if(o1.lastModified() > o2.lastModified()){
                    return -1;
                }else if(o1.lastModified() == o2.lastModified()){
                    return 0;
                }else{
                    return 1;
                }
            }
        });
     }

     /**
      * 调用静态方法
      * @param path
      * @return
      */
    public static List<File> fileReadLoop(String path) {
        FileLoop fileCon = new FileLoop();
        fileCon.loopReadDir(path);
        fileCon.sortFileList();
        return fileList;
    }
}
原文地址:https://www.cnblogs.com/shangrongyiweng/p/5915771.html