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.

2

2 Answers 2

4

You can also use Apache Commons FileUtis

FileUtils.listFiles(dir, extensions, true); 
Sign up to request clarification or add additional context in comments.

Comments

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.

8 Comments

This is not recursive, i. e. it does not search in sub-folders
Thanks, indeed I found an answer involving FilenameFilter in the question linked in the comment. But your solution is even shorter.
@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
Maybe I was not clear: I want it to recursively explore a directory tree, but without implementing myself a recursive method call.
Well, I understood that he still wants to search sub-folders (implicit recursion) simply by calling a method, i.e. without explicit recursion
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.