List directory and subdirectory files with listFiles

Asked

Viewed 7,595 times

2

Today I list through the code below the files that are in the directory passed by the parameter, but now I would like to list also the files that are in the subdirectories. I did some searches but I did not find anything that does not alter my structure much, also found that removing the isFile() I would, but it didn’t work.

void indexaArquivosDoDiretorio(File raiz) {
    FilenameFilter filtro = new FilenameFilter() {
        public boolean accept(File arquivo, String nome) {
            return nome.toLowerCase().endsWith(".pdf")
                    || nome.toLowerCase().endsWith(".odt")
                    || nome.toLowerCase().endsWith(".doc")
                    || nome.toLowerCase().endsWith(".docx")
                    || nome.toLowerCase().endsWith(".ppt")
                    || nome.toLowerCase().endsWith(".pptx")
                    || nome.toLowerCase().endsWith(".xls")
                    || nome.toLowerCase().endsWith(".txt")
                    || nome.toLowerCase().endsWith(".rtf");
        }
    };

    for (File arquivo : raiz.listFiles(filtro)) {
        if (arquivo.isFile()) {
            try {
                // Extrai o conteúdo do arquivo com o Tika;
                String textoExtraido = getTika().parseToString(arquivo);
                indexaArquivo(arquivo, textoExtraido);
                System.out.println(arquivo);
                i++;
            } catch (Exception e) {
                logger.error(e);
            }
        } else {
            indexaArquivosDoDiretorio(arquivo);
        }
    }
}
  • Now that I answered that I read the restriction com listFiles(). Should it be like this or does my answer answer? If it’s not a restriction, and it’s just a suggestion, could I change the title?

  • @Math I wanted with the listFiles() because I think it gets leaner. But thanks anyway for the contribution, I’ll take a look if it’s to learn.

  • 1

    No problem, I went in the excitement because I already knew this walkTreeFile(), rs.. If I have a little time I’ll look into this method you spoke of.

2 answers

3


You can browse a directory structure, subdirectories and files with the method:

Path walkFileTree(Path start, FileVisitor<? super Path> visitor)

You need to specify the initial directory and implement the Filevisitor interface to tell you exactly what information should be shown when you go through the directory or file in question.

An example:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

class MyFileVisitor extends SimpleFileVisitor<Path> {
    public FileVisitResult visitFile(Path path, BasicFileAttributes fileAttributes){
        System.out.println("Nome do arquivo:" + path.getFileName());
        return FileVisitResult.CONTINUE;
    }
    public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes fileAttributes){
        System.out.println("----------Nome do diretório:" + path + "----------");
        return FileVisitResult.CONTINUE;
    }
}

public class Walk {
    public static void main(String[] args) {
        Path source = Paths.get("C:\\Users\\Math\\Desktop");
        try {
            Files.walkFileTree(source, new MyFileVisitor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Source: Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805: A Comprehensive OCPJP 7 Certification Guide (Expert’s Voice in Java)

  • 2

    This is really the best way. And if you want an example of a utility class that locates a file in the subdirectories, see this one (go to the method findFile).

  • 1

    @utluiz Poisé, at first it may seem unnecessary and laborious to have to implement an interface "just" to go through directories, but I believe it is the cleanest and easiest way to develop and maintain. Thank you for your contribution!

1

I managed to solve my difficulty as follows: As I was already using a filter to show me the kind of files I was interested in, I came to the conclusion that the right place to check would be there. Then it dawned on me that a directory has no extension, so it would end up with "empty" the name, and that’s what I did. I added the line nome.toLowerCase().endsWith("") in my FilenameFilter and it worked.

That’s what the code looks like:

void indexaArquivosDoDiretorio(File raiz) {
        FilenameFilter filtro = new FilenameFilter() {
            public boolean accept(File arquivo, String nome) {
                return nome.toLowerCase().endsWith(".pdf")
                        || nome.toLowerCase().endsWith(".odt")
                        || nome.toLowerCase().endsWith(".doc")
                        || nome.toLowerCase().endsWith(".docx")
                        || nome.toLowerCase().endsWith(".ppt")
                        || nome.toLowerCase().endsWith(".pptx")
                        || nome.toLowerCase().endsWith(".xls")
                        || nome.toLowerCase().endsWith(".txt")
                        || nome.toLowerCase().endsWith(".rtf")
                        || nome.toLowerCase().endsWith("");
            }
        };

    for (File arquivo : raiz.listFiles(filtro)) {
        if (arquivo.isFile()) {
            try {
                // Extrai o conteúdo do arquivo com o Tika;
                String textoExtraido = getTika().parseToString(arquivo);
                indexaArquivo(arquivo, textoExtraido);
                System.out.println(arquivo);
                i++;
            } catch (Exception e) {
                logger.error(e);
            }
        } else {
            indexaArquivosDoDiretorio(arquivo);
        }
    }
}
  • People who have similar difficulty but can use newer versions of Java should consider using the Path class (see @Math’s response) instead of the File class as recommended in Legacy File I/O Code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.