List files in directory in java

In this article, we will explore different ways to list all files in a folder in java with methods from java 8.
Following are the methods covered

1. Using File.list()
java.io.File has a list() method which returns an array of string values. This array contains the names of file and folder inside the directory represented by the File object.
Iterating over this array will give the names of all the folder and files inside a directory. Example,

File folder = new File("D:\\myFolder");
String[] files = folder.list();
for (String file : files) {
  System.out.println(file);
}

2. File.listFiles()
There is a listFiles() method in java.io.File class which also returns an array of File objects.
Each file object represents a file or a folder. With this method, you can get the name or absolute path of each file or folder. Example,

File folder = new File("D:\\myFolder");
File[] files = folder.listFiles();
for (File file : files) {
  System.out.println(file.getAbsolutePath());
}

listFiles() will return null, if the given path is not a directory. So, we should check for null to avoid NullPointerException.

If you want to print only file names and avoid folders, then use isFile() method, which will return true if the given File object represents a file and false if it is a directory. Example,

File folder = new File("D:\\myFolder"); 
File[] files = folder.listFiles(); 
for (File file : files) { 
  if(file.isFile()) {
    System.out.println(file.getAbsolutePath()); 
  }
}

To achieve the same with java 8, we can use stream and filter() method as below

File folder = new File("d:\\work");
List<String> files = Stream.of(folder.listFiles()).
                      filter(f -> f.isFile()).
                      map(f -> f.getName())
          .collect(Collectors.toList());

To list all files inside nested directories as well, use the recursive approach as shown below

static void traveseFolder(File folder) {
  File[] files = folder.listFiles();
  for (File file : files) {
    if(file.isDirectory()) {
      traveseFolder(file);
    } else {
      System.out.println(file.getAbsolutePath());
    }
  }
}

Call this method with the File object for which you need to list files.
This method checks if a file object represents a directory and calls itself thereby listing the files and folders of nested sub-directory.

3. Java 8 Files.list()
java.nio.file.Files class belongs to Java NIO.
list() method was added to this class in java 8, which accepts a Path object and returns a stream of path objects which represent the files in the directory.
This stream is not recursive, meaning that it will only consist of files in the current directory. Example of this method is

Stream<Path> files = Files.list(Paths.get("D:\\work"));
files.forEach(f -> System.out.println(f.getFileName()));
files.close();

If you wish to list only files in a folder, then use below code

Stream<Path> paths = Files.list(Paths.get("D:\\work"));
List<File> files = paths.map(p -> p.toFile()).
                   filter(File::isFile).
                   collect(Collectors.toList());
paths.close();

where map() method is used to convert a Path object to a File object and filter() is used to return only files.
4. Java 8 Files.walk()
Java 8 added another method to java.nio.file.Files class.
This method is similar to list() in that it returns a stream of path objects but this method traverses a directory recursively.
This means that it will also list all files and folders inside nested sub-directories. Example,

Stream<Path> paths = Files.walk(Paths.get("D:\\work"));
List<File> files = paths.
                    map(p -> p.toFile()).
                    filter(File::isFile).
                    collect(Collectors.toList());
System.out.println(files);
paths.close();

If you want to list directories as well, then remove the filter() method.

With walk() method, you can also control the depth till which you want to list files. It has an overloaded method which takes an integer representing the depth.

Use below code to find all the files with a certain extension

Path dir = Paths.get("d:\\work");
try (Stream<Path> stream = Files.walk(dir)) {
  stream.
  filter(path -> path.toString().endsWith(".txt"))
  .forEach(System.out::println);
} catch(IOException e) {
  e.printStackTrace();
}

5. Using DirectoryStream
java.nio.file.DirectoryStream interface provides a convenient way to iterate over all files in a directory.

To use DirectoryStream to list all files in a directory, we need to get a reference to the directory.
This is done by using the Files.newDirectoryStream() method. It takes a Path object as an argument.

When we have a DirectoryStream object, we can use its iterator() method to obtain an iterator. This iterator is used to iterate over all the files in the directory. Example,

try (DirectoryStream<Path> stream = 
             Files.newDirectoryStream(Paths.get("D:\\myFolder"))) {
  for (Path file: stream) {
    System.out.println(file.getFileName());
  }
} catch (IOException e) {
  e.printStackTrace();
}

That is all on different ways to list all files in a folder or directory in java.