Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-recursive way to get all files in a directory and its subdirectories in Java

I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:

private void printFiles(File dir) {
  for (File child : dir.listFiles()) {
    if (child.isDirectory()) {
      printFiles(child);
    } else if (child.isFile()) {
      System.out.println(child.getPath());
    }
  }
}

printFiles(new File("somedir/somedir2"));

However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?

like image 460
K Mehta Avatar asked Jul 21 '11 12:07

K Mehta


People also ask

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.

How do I print all files in a folder recursively?

How to get a recursive directory listing in Linux or Unix. Try any one of the following commands to see recursive directory listing: ls -R : Use the ls command to get recursive directory listing on Linux. find /dir/ -print : Run the find command to see recursive directory listing in Linux.

What does recurse into directories mean?

Alternatively referred to as recursive, recurse is a term used to describe the procedure capable of being repeated. For example, when listing files in a Windows command prompt, you can use the dir /s command to recursively list all files in the current directory and any subdirectories.


2 Answers

You can always replace a recursive solution with an iterative one by using a stack (for DFS) or a Queue (For BFS):

private void printFiles(File dir) {
  Stack<File> stack = new Stack<File>();
  stack.push(dir);
  while(!stack.isEmpty()) {
    File child = stack.pop();
    if (child.isDirectory()) {
      for(File f : child.listFiles()) stack.push(f);
    } else if (child.isFile()) {
      System.out.println(child.getPath());
    }
  }
}

printFiles(new File("abc/def.ghi"));
like image 97
Ryan Gross Avatar answered Sep 24 '22 14:09

Ryan Gross


Java 8 onward, you can use Files#walk to list out all files and directories recursively in a given directory. Further you can apply the filter like Files::isRegularFile to filter out the directories if you need only regular files.

On the flip side, if you only need to list the given directory but not its sub-directories, you can use the lazy method Files#list which will only give you the files and directories in the given directory. You can again further apply the filter mentioned above.

like image 41
VHS Avatar answered Sep 23 '22 14:09

VHS