3

I implemented a recursive method to traverse a directory hierarchy looking for files with a given extension; however I'm not convinced this is the easiest way and it involves isDirectory(), listFiles(), etc.

Is there a way to do that without explicitly writing a recursive method: I'm thinking something like find that would directly return a list of files or filenames (with their full path) at any level in the structure matching the correct extension. I would then just loop over these files.

Any help appreciated.

Cedric H.
  • 7,980
  • 10
  • 55
  • 82

2 Answers2

4

You can also use Apache Commons FileUtis

FileUtils.listFiles(dir, extensions, true);
ravthiru
  • 8,878
  • 2
  • 43
  • 52
2

Use java.io.File#listFiles();

public File[] finder( String dirName){
    File dir = new File(dirName);
    return dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String filename){
            return filename.endsWith(".txt"); 
        }
    });
}

Edit: If you would like to discover the directory in recursive take a look at

FileUtilslistFiles(File directory, String[] extensions, boolean recursive)

with a filter.

Hash
  • 4,647
  • 5
  • 21
  • 39
  • 1
    This is not recursive, i. e. it does not search in sub-folders – AhmadWabbi Aug 24 '16 at 09:09
  • 1
    Thanks, indeed I found an answer involving `FilenameFilter` in the question linked in the comment. But your solution is even shorter. – Cedric H. Aug 24 '16 at 09:10
  • 1
    @AhmadWabbi the author asked explicitly for a *non* recursive and this is truly the most simple and fast (as this overload does not create a `File` object for every found file) way to achieve his goal – codejanovic Aug 24 '16 at 09:13
  • Maybe I was not clear: I want it to recursively explore a directory tree, but without implementing myself a recursive method call. – Cedric H. Aug 24 '16 at 09:14
  • 1
    Well, I understood that he still wants to search sub-folders (implicit recursion) simply by calling a method, i.e. without explicit recursion – AhmadWabbi Aug 24 '16 at 09:16
  • `FileUtils.listFiles` is better in both cases: recursive or not. – AhmadWabbi Aug 24 '16 at 09:21
  • Basically it does the same inside, but yes it takes less effort to use it. – Hash Aug 24 '16 at 09:23
  • Thanks that's exactly what I needed. – Cedric H. Aug 24 '16 at 12:18