Read Sub directory and specific files in Java

Saneth Chandrasekara :

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.

Jeppe :

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()));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148802&siteId=1