How to list all files in a directory in java

April 18, 2020 | No comments

Photo by Viktor Talashuk on Unsplash

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.
Get Files
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; 
  }
Files.walk
Files.walk returns a stream containing
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;
  }

Example

No comments :

Post a Comment

Please leave your message queries or suggetions.