Java 8 – List of All Files in a Directory

Learn to use Java 8 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 (map, filter, sorted, collect), use Files.list() instead.

1. Files.list() – Iterate over all files and sub-directories

Java example to iterate over a directory and get the List<File> using Files.list() method.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class IterateDirectoryExample {

	public static void main(String[] args) {

		String dirLocation = "C:/temp";

		try {
			List<File> files = Files.list(Paths.get(dirLocation))
						.map(Path::toFile)
						.collect(Collectors.toList());
			
			files.forEach(System.out::println);
		} catch (IOException e) {
			// Error while reading the directory
		}
	}
}

Program Output:

C:\temp\filename1.txt
C:\temp\directory1
C:\temp\filename2.txt
C:\temp\Employee.java

2. Files.list() – List only files excluding sub-directories

Use the filter expression Files::isRegularFile to check if a file is normal file, and not any directory.

String dirLocation = "C:/temp";

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

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

Program Output:

C:\temp\filename1.txt
C:\temp\filename2.txt
C:\temp\Employee.java

To list files in a different directory, we can replace "." with the full path of the directory we desire.

3. Files.newDirectoryStream() – List all files and sub-directories

Java provides a more flexible way of traversing a directory content using Files.newDirectoryStream().

Please note that if we’re working with a large directory, then using DirectoryStream actually make code faster.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class IterateDirectoryExample {

	public static void main(String[] args) {

		String dirLocation = "C:/temp";

		try {
			for (Path path : Files.newDirectoryStream(Paths.get(dirLocation))) {

				path = path.normalize();
				System.out.println(path.getFileName());
			}
		} catch (IOException e) {
			// Error while reading the directory
		}
	}
}

Program Output:

C:\temp\filename1.txt
C:\temp\directory1
C:\temp\filename2.txt
C:\temp\Employee.java

4. Files.newDirectoryStream() – Iterate only files excluding sub-directories

To loop through only the files and excluding all the sub-directories from the stream, use path filter isFile() as the second argument to the newDirectoryStream() constructor.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class IterateDirectoryExample {

	public static void main(String[] args) {

		String dirLocation = "C:/temp";

		try {
			for (Path path : Files.newDirectoryStream(Paths.get(dirLocation), 
						path -> path.toFile().isFile())) {

				path = path.normalize();
				System.out.println(path.getFileName());
			}
		} catch (IOException e) {
			// Error while reading the directory
		}
	}
}

Program Output:

C:\temp\filename1.txt
C:\temp\filename2.txt
C:\temp\Employee.java

5. List of all files of certain extention only

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

With the above predicate, we are listed all .java files in a folder.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class IterateDirectoryExample {

	public static void main(String[] args) {

		String dirLocation = "C:/temp";

		try {
			List<File> files = Files.list(Paths.get(dirLocation))
									.filter(Files::isRegularFile)
									.filter(path -> path.toString().endsWith(".java"))
									.map(Path::toFile)
									.collect(Collectors.toList());
			
			files.forEach(System.out::println);
		} catch (IOException e) {
			// Error while reading the directory
		}
	}
}

Program Output:

C:\temp\Employee.java

6. Finding all hidden files in a directory

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

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 !!

References:

DirectoryStream
Files.list() method

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “Java 8 – List of All Files in a Directory”

    • Files.newDirectoryStream(Paths.get(directory),
      path -> path.toFile().lastModified() > sd.getTime() && path.toFile().lastModified() < ed.getTime());

      Reply
  1. Here is the code for reading filename and store them in list.

    List fileNamesList = new ArrayList();
          Files.newDirectoryStream(Paths.get(dir), 
          path -> path.toString().endsWith(".java")).forEach(filePath -> fileNamesList.add(filePath.toString()));
    
    Reply
  2. I appreciate the post.

    But the code in “Find all hidden files in directory” section gives syntax error.

    And, its sad that you didn’t tell how to capture the file names in a list or something else (will be helpful for the people who are learning java 8). In real world, we don’t need to read the file names just to sysout.

    Reply
    • Here is the code for reading file names and store them in list.

      List fileNamesList = new ArrayList();
      		Files.newDirectoryStream(Paths.get(dir), path -> path.toString().endsWith(filenameFilter)).forEach(filePath -> fileNamesList.add(filePath.toString()));
      
      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.