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())); }
public boolean accept(File dir, String name)...- dir here refers to the parent directory the file was found in, so for alldir.isDirectory(), this will be true. FilenameFilter||means or, you need to use&&which means and