Listing All Files in a Directory in Java

Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

  • For using external iteration (for loop) use DirectoryStream.
  • For using Stream API operations, use Files.list() instead.

1. Listing Files Only in a Given Directory

1.1. Sream of Files with Files.list()

If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, then we can use this approach.

  • Read all files and directories entries using Files.list().
  • Check if a given entry is a file using Predicate File::isFile.
  • Collect all filtered entries into a List.
//The source directory
String directory = "C:/temp";

// Reading only files in the directory
try {
  List<File> files = Files.list(Paths.get(directory))
    .map(Path::toFile)
    .filter(File::isFile)
    .collect(Collectors.toList());

  files.forEach(System.out::println);
} catch (IOException e) {
  e.printStackTrace();
}

1.2. DirectoryStream to Loop through Files

DirectoryStream is part of Java 7 and is used to iterate over the entries in a directory in for-each loop style.

Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed.

List<File> fileList = new ArrayList<>();

try (DirectoryStream<Path> stream = Files
  .newDirectoryStream(Paths.get(directory))) {
  for (Path path : stream) {
    if (!Files.isDirectory(path)) {
      fileList.add(path.toFile());
    }
  }
}

fileList.forEach(System.out::println);

2. Listing All Files in Given Directory and Sub-directories

2.1. Files.walk() for Stream of Paths

The walk() method returns a Stream by walking the file tree beginning with a given starting file/directory in a depth-first manner.

Note that this method visits all levels of the file tree.

String directory = "C:/temp";
List<Path> pathList = new ArrayList<>();

try (Stream<Path> stream = Files.walk(Paths.get(directory))) {
  pathList = stream.map(Path::normalize)
        .filter(Files::isRegularFile)
        .collect(Collectors.toList());
}

pathList.forEach(System.out::println);

If you wish to include the list of Path instances for directories as well, then remove the filter condition Files::isRegularFile.

2.2. Simple Recursion

We can also write the file tree walking logic using the recursion. It gives a little more flexibility if we want to perform some intermediate steps/checks before adding the entry to list of the files.

String directory = "C:/temp";

//Recursively list all files
List<File> fileList = listFiles(directory);

fileList.forEach(System.out::println);

private static List<File> listFiles(final String directory) {
    if (directory == null) {
      return Collections.EMPTY_LIST;
    }
    List<File> fileList = new ArrayList<>();
    File[] files = new File(directory).listFiles();
    for (File element : files) {
      if (element.isDirectory()) {
        fileList.addAll(listFiles(element.getPath()));
      } else {
        fileList.add(element);
      }
    }
    return fileList;
}

Please note that if we’re working with a large directory, then using DirectoryStream performs better.

3. Listing All Files of a Certain Extention

To get the list of all files of certain extensions only, use two predicates Files::isRegularFile and filename.endsWith(".extension") together.

In given example, we are listing all .java files in a given directory and all of its sub-directories.

String directory = "C:/temp";

//Recursively list all files
List<Path> pathList = new ArrayList<>();

try (Stream<Path> stream = Files.walk(Paths.get(directory))) {
      // Do something with the stream.
      pathList = stream.map(Path::normalize)
        .filter(Files::isRegularFile)
        .filter(path -> path.getFileName().toString().endsWith(".java"))
        .collect(Collectors.toList());
    }
    pathList.forEach(System.out::println);
}

4. Listing All Hidden Files

To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples.

List<File> files = Files.list(Paths.get(dirLocation))
      .filter(path -> path.toFile().isHidden())
      .map(Path::toFile)
      .collect(Collectors.toList());

In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods. Feel free to modify the code and play with it.

Happy Learning !!

Sourcecode on Github

Leave a Reply

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial