- How to list all files in a directory in Java
- You might also like.
- Java 8 List all Files in Directory and Subdirectories
- Note
- How to get list of all files/folders from a folder in Java?
- The List() method
- Example
- Output
- The ListFiles() method
- Example
- Output
- The List(FilenameFilter filter) method
- Example
- Output
- The ListFiles(FilenameFilter filter) method
- Example
- Output
- The ListFiles(FileFilter filter) method
- Example
- Output
- Java – How to list all files in a directory?
- 1. Files.walk
- 2. Classic
- References
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.
You might also like.
Java 8 List all Files in Directory and Subdirectories
Files.walk Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
Files.list Method Return a lazily populated Stream for the current directory only, Files.walk can be used to get list of files from Directory & Subdirectories .
Example 1: List All Files in Directory and Subdirectories
public static void main(String[] args) throws IOException {
Path start = Paths.get(«C:\\data\\»);
try (Stream stream = Files.walk(start, Integer.MAX_VALUE)) {
List collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
Note
Files.walk method takes int maxDepth as parameter. The maxDepth parameter is the maximum number of levels of directories to visit.
MAX_VALUE may be used to indicate that all levels should be visited. Value 1 can be used to list files in current Directory.
Example 2: List All Files in Current Directory only
public static void main(String[] args) throws IOException {
Path start = Paths.get(«C:\\data\\»);
try (Stream stream = Files.walk(start, 1)) {
List collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
How to get list of all files/folders from a folder in Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
To get the list of all the existing files in a directory this class provides the files class provides list() (returns names) and ListFiles (returns File objects) with different variants.
The List() method
This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object.
Using this method, you can just print the names of the files and directories.
Example
The following Java program lists the names of all the files and directories in the path D:\ExampleDirectory.
import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories String contents[] = directoryPath.list(); System.out.println("List of files and directories in the specified directory:"); for(int i=0; i> >
Output
List of files and directories in the specified directory: SampleDirectory1 SampleDirectory2 SampleFile1.txt SampleFile2.txt SapmleFile3.txt
The ListFiles() method
This method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
Since this method returns the objects of each file/directory in a folder. Using it you can access the properties of the files/directories such as size, path etc.
Example
The following Java program prints the name, path and, size of all the files in the path D:\ExampleDirectory.
import java.io.File; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //List of all files and directories File filesList[] = directoryPath.listFiles(); System.out.println("List of files and directories in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >
Output
List of files and directories in the specified directory: File name: SampleDirectory1 File path: D:\ExampleDirectory\SampleDirectory1 Size :262538260480 File name: SampleDirectory2 File path: D:\ExampleDirectory\SampleDirectory2 Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480
The List(FilenameFilter filter) method
As suggested in its signature, this method accepts a FilenameFilter object and returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter.
Using this method, you can get the filtered names of the files and directories in a particular folder.
Example
The following Java program prints the names of the text files in the path D:\ExampleDirectory.
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files String filesList[] = directoryPath.list(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(String fileName : filesList) < System.out.println(fileName); >> >
Output
List of the text files in the specified directory −
SampleFile1.txt SampleFile2.txt SapmleFile3.txt
The ListFiles(FilenameFilter filter) method
This method accepts a FilenameFilter object and returns a File array containing the objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on their name
Using this method, you can get the filtered file objects of the files and directories in a particular folder, according to their names.
Example
The following Java program prints the name, path and, size of all the text files in the path D:\ExampleDirectory.
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >
Output
List of the text files in the specified directory: File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480
The ListFiles(FileFilter filter) method
This method accepts a FileFilter object and returns a File array containing the (File) objects of all the files and directories in the path represented by the current File object. But the retuned array contains the files (objects) which are filtered based on the property of the file.
Using this method, you can get the filtered file objects of the files and directories in a particular folder based on the size, path, type (file or, directory) etc…
Example
The following Java program prints the name, path and, size of all the files (not folders) in the path D:\ExampleDirectory.
import java.io.File; import java.io.FileFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FileFilter textFilefilter = new FileFilter()< public boolean accept(File file) < boolean isFile = file.isFile(); if (isFile) < return true; >else < return false; >> >; //List of all the text files File filesList[] = directoryPath.listFiles(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(File file : filesList) < System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println("Size :"+file.getTotalSpace()); System.out.println(" "); >> >
Output
List of the text files in the specified directory: File name: cassandra_logo.jpg File path: D:\ExampleDirectory\cassandra_logo.jpg Size :262538260480 File name: cat.jpg File path: D:\ExampleDirectory\cat.jpg Size :262538260480 File name: coffeescript_logo.jpg File path: D:\ExampleDirectory\coffeescript_logo.jpg Size :262538260480 File name: javafx_logo.jpg File path: D:\ExampleDirectory\javafx_logo.jpg Size :262538260480 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt Size :262538260480 File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt Size :262538260480 File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt Size :262538260480
Java – How to list all files in a directory?
Two Java examples to show you how to list files in a directory :
1. Files.walk
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.filter(Files::isDirectory) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)
1.3 List all files end with .java
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.map(x -> x.toString()) .filter(f -> f.endsWith(".java")).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)
1.4 Find a file – HeaderAnalyzer.java
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.map(x -> x.toString()) .filter(f -> f.contains("HeaderAnalyzer.java")) .collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)
2. Classic
In the old days, we can create a recursive loop to implement the search file function like this :
2.1 List all files end with .java
package com.mkyong.example; import java.io.File; import java.util.ArrayList; import java.util.List; public class JavaExample < public static void main(String[] args) < final File folder = new File("C:\\projects"); Listresult = new ArrayList<>(); search(".*\\.java", folder, result); for (String s : result) < System.out.println(s); >> public static void search(final String pattern, final File folder, List result) < for (final File f : folder.listFiles()) < if (f.isDirectory()) < search(pattern, f, result); >if (f.isFile()) < if (f.getName().matches(pattern)) < result.add(f.getAbsolutePath()); >> > > >
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.