How to get all the files in a directory and subdirectories in java

The files in a directory and its sub directories are listed using a recursive method.

The method lists the files in the current directory, then it calls itself recursively for all the sub directories.

Create the following java file:


public class FolderListAllFilesDirectory {
    public static void listAllFiles(File file){
	// List all the files using the filter
	File[] tab = file.listFiles();
	for( File current : tab ){
	    if( current.isFile() )
		System.out.println( current.getAbsolutePath() + " is a file " );
	    else if( current.isDirectory() ){
		listAllFiles( current );

    public static void main(String[] argv) {

	File file = new File("V:/tmp/aaa");

	listAllFiles( file );


The output will be:

V:\tmp\aaa\New Text Document.txt is a file 
V:\tmp\aaa\\index.html is a file 
V:\tmp\aaa\\test\test.txt is a file 
V:\tmp\aaa\\test.html is a file 

The method displayed the files and process each sub directory as they are returned by the file system. The method can be modified to process by breadth first, the files are returned first. Or the method can process by depth first: the directories and sub directories are processed first.


java 8 File

Share this article:

Recent Comments