How to list all files in a directory in java

April 18, 2020 | No comments

How to list all files in a directory in java

Say we want get names of all the files under a directory and sub directories. Basically we need to able to look under each sub directory and if it has any files add to the result. This sounds like a problem that can be solved recursively.
In the following section we have two different methods doing the same thing. Example 1 we are creating a File object with given path and iterating over its contents. And if the content is file we are adding it to return list.
List the file names by calling listFiles on the root path, and then recursively calling it if we get any directory.
public List getFiles (String path) {
     List result = new ArrayList();
     File root = new File (path);
     File[] filesNDirectories = root.listFiles();
     
     for (var file: filesNDirectories) {
       if (file.isFile()) {
         result.add(file.getName());
       } 
       else if (file.isDirectory()) {
         List subResult = getFiles(file.getPath());
         result.addAll(subResult);
       }
     }
     return result; 
  }
In the second example we are creating a Stream from the given path. Using functional programming (lambda), filtering all the files from the stream and collecting file name in the returned list. We are using Files::isRegularFile method reference to invoke the static method isRegularFile.
Files.walk returns a stream containing children. This method is essentially returns the same content as the above method.
public List getFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isRegularFile).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }

No comments :

Post a Comment

Please leave your message queries or suggetions.

Note: Only a member of this blog may post a comment.