Java File uses recursion to get all files in the folder

Java File uses recursion to get all files in the folder

File method:
Extract the File method in the API

Problem-solving ideas:
1. Determine whether the file path exists or not, directly end the method
2. The file exists, turn it into a file array,
3. Traverse the array to name the file, use the endsWith() method of the String class to determine whether the file suffix is .txt
4. If yes, use recursion, call your own method, and continue to take the file name
(the collection is set as a global static attribute: static characteristics, loaded as the class is loaded, there is only one in memory Copies)
Code display:

//全局静态属性,集合用来存储所有的文件名
  static ArrayList<String> arrs = new ArrayList<>();
    public static ArrayList job1(File file){
    
    
        if(file.exists()) {
    
    
            //获取文件数组
            File[] files = file.listFiles();
            //遍历文件数组,获得文件名
            for (File f : files) {
    
    
                //判断名字是不是。txt结尾
                if (f.getName().endsWith(".txt")) {
    
    
                    arrs.add(f.getName());
                } else {
    
    
                    job1(f);
                }
            }
            return arrs;
        }
        System.out.println("文件路径错误");
        return null;
    }

Guess you like

Origin blog.csdn.net/CV_Ming/article/details/112325581