List all files, subdirectories with Java

In the previous tutorial, we learned together how to list files and folders in a certain folder but only for the folder we want. If you want to list all the subdirectories in this directory as well, because a directory can contain many subdirectories and those subdirectories can also contain many other subdirectories, you can use the static walk() method of the Files class to do this.

This walk() method has 2 overloading methods:


For the walk(Path start, int maxDepth, FileVisitOption… options) method, the first parameter is the directory that you need to list.

The second parameter relates to the level you want to enumerate. For example, your folder contains subfolders, one subfolder contains other subfolders, another subfolder contains other subfolders, etc. The level you want to list, you can declare using this 2nd parameter. Its value starts from the value of 1! If a value of 0, the result will be the directory you passed in. And a negative value will be reported an error.

The third parameter is related to the options we want to do with the directories, and files we list. Currently, Java allows us to configure whether we need to list symbolic link directories or not:

By default, if we do not declare this parameter, we will not list symbolic links!

The walk(Path start, FileVisitOption… options) method has the same parameters as I said above. Only thing is, the maxDepth parameter will default to Integer.MAX_VALUE (equivalent to 2^31-1), which means it will list all directories and files.

For example, if I want to list files and subdirectories of a directory with a level of 2, I can write the following code:

When you run this example code, you will see the following output:

As you can see, the directory mule-esb-dynamic-property and all the directories and files in this directory are listed.

If you want to add some operations to some files or directories when listing, you can also use the static walkFileTree() method of the Files class.

This method also has 2 overloading methods:


Parameters start, options and maxDepth, I already mentioned above. Here, we have an extra parameter named “visitor” of the FileVisitor interface. This parameter helps us to add operations to the files, before and after listing a directory we want.

The content of this FileVisitor interface is as follows:

The implementation of the FileVisitor interface is the SimpleFileVisitor class! Please override these abstract methods according to your needs!

For example, if I just want to print out all the directories in the example directory, I will write the following code:


FileVisitResult enum makes it possible for us to adjust whether to continue the enumeration or stop. Depending on your needs, please use it correctly!

Add Comment