Recursively search for a directory in Java

后端 未结 7 2195
深忆病人
深忆病人 2021-01-05 10:45

What is the best way to find a directory with a specific name in Java? The directory that I am looking for can be located either in the current directory or one of its subdi

7条回答
  •  忘掉有多难
    2021-01-05 10:58

    Or, you should use the concept of Recursively search the file until it found: Here is the Code:

    String name; //to hold the search file name
    
    public String listFolder(File dir) {
        int flag;
        File[] subDirs = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        });
        System.out.println("File of Directory: " + dir.getAbsolutePath());
        flag = Listfile(dir);
        if (flag == 0) {
            System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
            Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
            return dir.getAbsolutePath();
        }
        for (File folder : subDirs) {
            listFolder(folder);
        }
        return null;
    }
    
    private int Listfile(File dir) {
        boolean ch = false;
        File[] files = dir.listFiles();
        for (File file : files) {
            Listfile(file);
            if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
                System.out.println(name + "Found Sucessfully!!");
                ch = true;
    
            }
        }
        if (ch) {
            return 1;
        } else {
            return 0;
        }
    }
    

提交回复
热议问题