Make recursive search in all directories and subdirectories of a given folder

3

I am developing a script to scan a certain folder to search for certain files and delete them or move them to another folder, according to some rules that have already answered this question and on this other question .

My idea was to abstract this search, saving all the files found (either to move or to delete) in a list and later to make a decision about the operation, but I do not have much idea how to do a search in a certain folder and all your internal directory tree being found.

private static List<File> listarArquivos(File source, boolean condicao) {
    List<File> fileList = new ArrayList<>();

    File[] list = source.listFiles();

    for (File fl : list) {
        if (condicao) {
            fileList.add(fl);
            System.out.println(fl);
        }
    }

    return fileList;

}

This method only lists subfolders and files in the main directory, but does not list more internal files and folders, how to do this recursively?

    

asked by anonymous 02.12.2016 / 12:16

2 answers

2

Using Java 8 you can use the walk method of class Files :

List<Path> lista = new ArrayList<>();

Files.walk(Paths.get("C:/D/Desktop/Workshop"))
        .filter(arquivo -> this.filtrar(arquivo))
        .forEach(lista::add);

Or if you wanted to return a list of File :

List<File> lista = new ArrayList<>();

Files.walk(Paths.get("C:/D/Desktop/Workshop"))
        .filter(arquivo -> this.filtrar(arquivo))
        .forEach(arquivo -> {
          lista.add(arquivo.toFile());
        });

Whereas the filtrar method is like this (based on

02.12.2016 / 13:48
6

Just do a check if fl is a directory using File.isDirectory() and call the method again passing fl as a parameter.

private static List<File> listarArquivos(File source) 
{
    List<File> fileList = new ArrayList<>();

    File[] list = source.listFiles();

    for (File fl : list) {
        if (!fl.isDirectory()) {
            fileList.add(fl);
            System.out.println(fl);
        }else{
            System.out.println(String.format("** Pasta: %s **", fl));
            listarArquivos(fl);
        }
    }

    return fileList;
}
    
02.12.2016 / 12:44