How toList all files in directory – 6 examples

1. Overview

In this article we will look at Files class’s list method. list() method returns the content of directory passed in parameter. The contents are returned lazily in Stream object that contains Path to all the contents in directory.

The listing returned in Stream is not recursive. Which means that the listing provided will not navigate directory/directories.

To walk into multiple directories from this directory you will need to use Files.walk method. That will be covered in different articles.

2. list() method

list() method accepts java.nio.file.Path as parameter.

The below example pulls in the files and folder from directory. There is no recursive traversal if folder is encountered.

Files.list(Paths.get(".")).forEach(System.out::println);
 
Output:
./file1.txt
./target
./pom.xml
./.classpath
./.gitignore
./.settings
./.project
./src

3. lines() method on src/main/resources

String path = getClass().getResource("/Text-Files")
                        .toURI().getPath();
 
Files.list(Paths.get(path)).forEach(System.out::println);

4. Get regular files from directory

Files
	.list(Paths.get(path))
	.filter(Files::isRegularFile)
	.forEach(System.out::println);

5. Get text files from directory

String resourcesPath = getClass().getResource("/dir")
                                 .toURI().getPath();
 
Files
	.list(Paths.get(resourcesPath))
	.filter(path -> path.getFileName().toString().endsWith("txt"))
	.forEach(System.out::println);

6. Get text or JSON files from directory

Predicate<Path> extPredicate(String extension) {
	return path -> path.getFileName()
					.toString().endsWith(extension);
}
 
Files
	.list(Paths.get(resourcesPath))
	.filter(extPredicate("txt").or(extPredicate("json")))
	.forEach(System.out::println);

7. Read all lines from text files from directory

String resourcesPath = FilesClassListMethod.class
										.getResource("/Text-Files")
										.toURI().getPath();
 
Files
	.list(Paths.get(resourcesPath))
	.filter(predicate("txt"))
	.flatMap(path -> uncheckedReading(path).stream())
	.forEach(System.out::println);
 
private List<String> uncheckedReading(Path path) {
	try {
		return Files.readAllLines(path);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
     
Predicate<Path> predicate(String extension) {
	return path -> path.getFileName()
					.toString().endsWith(extension);
}

8. Conclusion

In this article, we saw how to use list() method to read all the content from the directory. Feel free to play around using different examples. list() is a powerful method as it allows us to use all the methods of Stream interface.

Leave a Reply

Your email address will not be published. Required fields are marked *