Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all files from a directory recursively with Java

Tags:

java

file-io

I have this function that prints the name of all the files in a directory recursively. The problem is that my code is very slow because it has to access a remote network device with every iteration.

My plan is to first load all the files from the directory recursively and then after that go through all files with the regex to filter out all the files I don't want. Does anyone have a better suggestion?

public static printFnames(String sDir) {     File[] faFiles = new File(sDir).listFiles();     for (File file : faFiles) {         if (file.getName().matches("^(.*?)")) {             System.out.println(file.getAbsolutePath());         }         if (file.isDirectory()) {             printFnames(file.getAbsolutePath());         }     } } 

This is just a test later on I'm not going to use the code like this, instead I'm going to add the path and modification date of every file which matches an advanced regex to an array.

like image 345
Hultner Avatar asked Mar 28 '10 21:03

Hultner


People also ask

How do I list all files in a directory recursively?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.

How do you get the names of all files in a folder in Java?

The List() method. This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object. Using this method, you can just print the names of the files and directories.

Are files walk recursive?

Files. walk returns a stream that is lazily populated with Path by recursively walking the file tree rooted at a given starting file. The file tree is traversed depth-first.

What does the files list () in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.


2 Answers

Assuming this is actual production code you'll be writing, then I suggest using the solution to this sort of thing that's already been solved - Apache Commons IO, specifically FileUtils.listFiles(). It handles nested directories, filters (based on name, modification time, etc).

For example, for your regex:

Collection files = FileUtils.listFiles(   dir,    new RegexFileFilter("^(.*?)"),    DirectoryFileFilter.DIRECTORY ); 

This will recursively search for files matching the ^(.*?) regex, returning the results as a collection.

It's worth noting that this will be no faster than rolling your own code, it's doing the same thing - trawling a filesystem in Java is just slow. The difference is, the Apache Commons version will have no bugs in it.

like image 154
skaffman Avatar answered Oct 06 '22 00:10

skaffman


In Java 8, it's a 1-liner via Files.find() with an arbitrarily large depth (eg 999) and BasicFileAttributes of isRegularFile()

public static printFnames(String sDir) {     Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println); } 

To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:

(p, bfa) -> bfa.isRegularFile()   && p.getFileName().toString().matches(".*\\.jpg")   && bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000 
like image 42
Bohemian Avatar answered Oct 06 '22 00:10

Bohemian