2

I need find all the java files in a directory

 private void search(File directory) { if (directory.isDirectory()) { File[] javaFilesLs = directory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".java"); // return name.toLowerCase().endsWith(".java") || dir.isDirectory(); } }); if (directory.canRead()) { assert javaFilesLs != null; for (File temp : javaFilesLs) { if (temp.isDirectory()) { search(temp); } else { fileList.add(temp.getAbsolutePath()); } } } } } 

When I use the commented line it finds the subdirectory and all the files not only ".java" files.

3
  • public boolean accept(File dir, String name)... - dir here refers to the parent directory the file was found in, so for all dir.isDirectory(), this will be true. FilenameFilter Commented May 26, 2019 at 9:04
  • || means or, you need to use && which means and Commented May 26, 2019 at 9:22
  • What is your end goal with this? Trying to read all the files that end with .java? Commented May 26, 2019 at 9:44

1 Answer 1

2

The reason why you get all paths using the commented line, is that dir.isDirectory() will return true for all files. Take a look at the documentation of FilenameFilter. It specifies that dir is "the directory in which the file was found."

So instead of looking at dir, you must test if name represents a directory. There may be smarter methods, but it can be done like this:

new File(dir.toPath().toString(), name).isDirectory() // returns true for directories 

The whole snippet thus looks like this:

private void search(File directory) { if (directory.isDirectory()) { File[] javaFilesLs = directory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".java") || new File(dir.toPath().toString(), name).isDirectory(); } }); if (directory.canRead()) { assert javaFilesLs != null; for (File temp : javaFilesLs) { if (temp.isDirectory()) { search(temp); } else { fileList.add(temp.getAbsolutePath()); } } } } } 

Alternatively, Java 8 adds Files.walk which implements the recursion for you as a Stream.

private void search(File directory) throws IOException { Files.walk(directory.toPath()) .filter(f -> { return f.getFileName().toString().endsWith(".java"); }) .forEach(f -> fileList.add(f.toFile().getAbsolutePath())); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.