list() and walk() Method Of Files Factory class In Java 8

As part of Java I/O package enhancements, we also have new list() and walk() method in File Factory class in Java 8 that will open a stream on that path directly for me. We will see both new method uses through an example. As we have some new methods in Java 8 to work with file systems, I also can read directories entries.

Example-1) Reading Directories Entries Using Files.list() Method

Output of the Example 1:

I open a Stream in my example, but this time on the path that points to a directory named “Program Files” on the file systems. Then I get list method from File Factory class, which is stream of path. This stream of path will contain every file and directory inside “Program Files” directory which I am opening. So I can filter out all files which is a directory and can printout them. But this list() method visit only first level of directories entries. It will not enter into sub directory if it is find inside a directory.

Example-2) Reading Directories Entries Using Files.walk() Method

To visit the whole sub-tree, use the Files.walk() method that also takes path as a parameter. Now if this path is a directory than it will return stream of path, the same kind in previous code example. But this time it will also explore sub-directories if there is any.

Output of the Example 2:

I also can restrict the depth of exploration. Suppose I only want to traverse second level sub directories and not the other. This is very simple, we just need to pass depth of exploration in walk() method as a second parameter.

Output of the above programme


Leave a Reply