Recursively list files in Java

后端 未结 27 1628
走了就别回头了
走了就别回头了 2020-11-22 00:29

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the fra

27条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:53

    public static String getExten(String path) {
        int i = path.lastIndexOf('.');
        if (i > 0) {
           return path.substring(i);
        }
        else return "";
    }
    public static List GetAllFiles(String path, ListfileList){
        File file = new File(path);
        
        File[] files = file.listFiles();
        for(File folder:files) {
            if(extensions.contains(getExten(folder.getPath()))) {
                fileList.add(folder.getPath());
            }
        }
        File[] direcs = file.listFiles(File::isDirectory);
        for(File dir:direcs) {
            GetAllFiles(dir.getPath(),fileList);
        }
        return fileList;
        
    }
    

    This is a simple recursive function that should give you all the files. extensions is a list of string that contains only those extensions which are accepted. Example extensions = [".txt",".docx"] etc.

提交回复
热议问题