Java Files.list
Java Files.list tutorial shows how to list files in Java with Files.list .
Files.list returns a lazily populated stream of directory elements. The listing is not recursive.
The elements of the stream are Path objects.
Files.list current directory
The first example lists the current directory.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx < public static void main(String[] args) throws IOException < Files.list(Paths.get(".")) .forEach(path ->System.out.println(path)); > >
The dot symbol represents the current working directory. We get the path object with Paths.get .
Files.list directories
The following example lists directories in the user’s home directory.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class FilesListEx2 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home"); Files.list(new File(homeDir).toPath()) .filter(path ->path.toFile().isDirectory()) .forEach(System.out::println); > >
We convert the path object to a File with toFile and call the isDirectory method. The stream is filtered with filter .
Files.list by file extensions
The next program lists all PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx3 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; Files.list(Paths.get(homeDir)).filter(path ->path.toString().endsWith(".pdf")) .forEach(System.out::println); > >
The program lists PDF files in the Downloads directory. The path object is converted to a string and we call endsWith on the string to check if it ends with pdf extension.
Files.list count files
We count the number of PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx4 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; var nOfPdfFiles = Files.list(Paths.get(homeDir)).filter(path ->path.toString() .endsWith(".pdf")).count(); System.out.printf("There are %d PDF files", nOfPdfFiles); > >
The number of files is determined with count .
In this article we have used Files.list to list the directory contents.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
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 PredicateFile::isFile.
- Collect all filtered entries into a List.
//The source directory String directory = "C:/temp"; // Reading only files in the directory try < Listfiles = Files.list(Paths.get(directory)) .map(Path::toFile) .filter(File::isFile) .collect(Collectors.toList()); files.forEach(System.out::println); > catch (IOException e)
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 fileList = new ArrayList<>(); try (DirectoryStream 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 pathList = new ArrayList<>(); try (Stream 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.
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 fileList = listFiles(directory); fileList.forEach(System.out::println); private static List listFiles(final String directory) < if (directory == null) < return Collections.EMPTY_LIST; >List 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 pathList = new ArrayList<>(); try (Stream 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 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.
How to list all files in a directory in Java
In Java, there are many ways to list all files and folders in a directory. You can use either the Files.walk() , Files.list() , or File.listFiles() method to iterate over all the files available in a certain directory.
The Files.walk() is another static method from the NIO API to list all files and sub-directories in a directory. This method throws a NoSuchFileException exception if the folder doesn’t exist. Here is an example that lists all files and sub-directories in a directory called ~/java-runner :
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // print all files and folders paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
Since it returns a Stream object, you can filter out nested directories and only list regular files like below:
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // filer out sub-directories ListString> files = paths.filter(x -> Files.isRegularFile(x)) .map(Path::toString) .collect(Collectors.toList()); // print all files files.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // filer out regular files ListString> folders = paths.filter(x -> Files.isDirectory(x)) .map(Path::toString) .collect(Collectors.toList()); // print all folders folders.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"))) // keep only `.java` files ListString> javaFiles = paths.map(Path::toString) .filter(x -> x.endsWith(".java")) .collect(Collectors.toList()); // print all files javaFiles.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
By default, the Stream object returned by Files.walk() recursively walks through the file tree up to an n-level (all nested files and folders). However, you can pass another parameter to Files.walk() to limit the maximum number of directory levels to visit. Here is an example that restricts the directory level to a top-level folder only (level 1):
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"), 1)) // print all files and folders in the current folder paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
In the above code, the second parameter of Fils.walk() is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of Integer.MAX_VALUE indicatea that all levels should be traversed.
The Files.list() static method from NIO API provides the simplest way to list the names of all files and folders in a given directory:
try (StreamPath> paths = Files.list(Paths.get("~/java-runner"))) // print all files and folders paths.forEach(System.out::println); > catch (IOException ex) ex.printStackTrace(); >
The Files.list() method returns a lazily populated Stream of entries in the directory. So you can apply all the above filters for Files.walk() on the stream.
In old Java versions (JDK 6 and below), the File.listFiles() method is available to list all files and nested folders in a directory. Here is an example that uses File.listFiles() to print all files and folders in the given directory:
File folder = new File("~/java-runner"); // list all files for (File file : folder.listFiles()) System.out.println(file); >
File folder = new File("~/java-runner"); // list all regular files for (File file : folder.listFiles()) if (file.isFile()) System.out.println(file); > >
File folder = new File("~/java-runner"); // list all sub-directories for (File file : folder.listFiles()) if (file.isDirectory()) System.out.println(file); > >
public void listFilesRecursive(File folder) for (final File file : folder.listFiles()) if (file.isDirectory()) // uncomment this to list folders too // System.out.println(file); listFilesRecursive(file); > else System.out.println(file); > > > // list files recursively File folder = new File("~/java-runner"); listFilesRecursive(folder);
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.