- Get list of files and sub-directories in a directory in Java
- Java – Filter files or sub-directories in a directory
- Extract list of files and sub-directories in a directory
- Get list of files of specific extension from the directory
- Get list of files with specific extension from the directory and its sub-directories
- Conclusion
- How to list all files in a directory in Java
- You might also like.
- Java 8 List all Files in Directory and Subdirectories
- Note
Get list of files and sub-directories in a directory in Java
In this Java tutorial, you will learn how to get the list of files and sub-directories in a given folder, with examples.
Java – Filter files or sub-directories in a directory
You can get the list of files and sub-directories in a given folder using Java. We can also filter the list based on extension or a specific condition.
In this Java Tutorial, we shall learn how to perform the following tasks.
- Extract list of files and directories in a folder using java
- Extract list of files belonging to specific file type
- Extract list of files belonging to specific file type, present in the folder and its sub folders/directories
Extract list of files and sub-directories in a directory
Follow these steps to extract the names of files and sub directories in a given directory.
Step 1 : Specify the folder. In this example, “sample” is the folder name placed at the root to the project.
File folder = new File("sample");
Step 2 : Get the list of all items in the folder.
File[] listOfFiles = folder.listFiles();
Step 3 : Check if an item in the folder is a file.
Step 4 : Check if an item in the folder is a directory.
Complete program that lists the files and directories in a folder is given below.
ListOfFilesExample.java
import java.io.File; import java.util.ArrayList; import java.util.List; /** * Program that gives list of files or directories in a folder using Java */ public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < files.add(listOfFiles[i].getName()); >else if (listOfFiles[i].isDirectory()) < directories.add(listOfFiles[i].getName()); >> System.out.println("List of files :\n---------------"); for(String fName: files) System.out.println(fName); System.out.println("\nList of directories :\n---------------------"); for(String dName: directories) System.out.println(dName); > >
The sample folder and its contents are as shown in the below picture :
When the program is run, output to the console would be as shown below.
List of files : --------------- html_file_1.html text_file_1.txt text_file_3.txt text_file_2.txt List of directories : --------------------- directory_1 directory_2
Get list of files of specific extension from the directory
Step 1 : Specify the folder.
File folder = new File("sample");
Step 2 : Get the list of all items in the folder.
File[] listOfFiles = folder.listFiles();
Step 3 : Check if an item in the folder is a file.
Step 4 : Check if the file belong to specified file-type.
Check the extension of the filename with String.endsWith(suffix)
listOfFiles[i].getName().endsWith(fileExtension)
Complete program to get the list of files, that belong to a specified extension type is shown below.
ListOfFilesExample.java
import java.io.File; import java.util.ArrayList; import java.util.List; public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); String fileExtension = ".txt"; File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< files.add(listOfFiles[i].getName()); >> > System.out.println("List of .txt files :\n--------------------"); for(String fName: files) System.out.println(fName); > >
When the program is run, Output to the console would be as shown below.
List of .txt files : -------------------- text_file_1.txt text_file_3.txt text_file_2.txt
Get list of files with specific extension from the directory and its sub-directories
Step 1 : Specify the folder.
File folder = new File("D:"+File.separator+"Arjun"+File.separator+"sample");
Step 2 : Get the list of all items in the folder.
File[] listOfFiles = folder.listFiles();
Step 3 : Check if an item in the folder is a file.
Step 4 : Check if the file belong to specified file-type.
Check the extension of the filename with String.endsWith(suffix)
listOfFiles[i].getName().endsWith(fileExtension)
Step 5 : Check if an item in the folder is a directory.
Step 6 : Get the list of files (beloging to specific file-type) recursively from all the sub-directories.
The complete program is given below.
FileListExtractor.java
import java.io.File; import java.util.ArrayList; import java.util.List; public class FileListExtractor < List allTextFiles = new ArrayList(); String fileExtension = ".txt"; public static void main(String[] args) < FileListExtractor folderCrawler = new FileListExtractor(); folderCrawler.crawlFold("sample"); System.out.println("All text files in the folder \"sample\" and its sub directories are :\n---------------------------------------------------------------"); for(String textFileName:folderCrawler.allTextFiles)< System.out.println(textFileName); >> public void crawlFold(String path) < File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< allTextFiles.add(listOfFiles[i].getName()); >> else if (listOfFiles[i].isDirectory()) < // if a directory is found, crawl the directory to get text files crawlFold(path+File.separator+listOfFiles[i].getName()); >> > >
When the program is run, output to the console is
All text files in the folder "sample" and its sub directories are : --------------------------------------------------------------- text_file_2_1.txt text_file_1_1.txt text_file_2_1.txt text_file_1_1.txt text_file_2_2.txt text_file_1_2.txt text_file_1.txt text_file_3.txt text_file_2.txt
Conclusion
In this Java Tutorial, we learned how to list all the files and sub-directories in a given folder.
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);
}
}