Skip to toolbar

File Handling || Traverse folders and subfolders in Java.

As we all know that we can read or write data on any format of file whether it is excel, word, notepad. But sometimes we need to traverse folders and subfolders to locate any file. Also, sometimes we need to identify the file folder count under specific directory, find a file with specific name, find duplicate instances of same file etc as per the requirements. We can achieve all these in Java using File class.

File Traversing
File Traversing

Traverse Folders and subfolders

This can be achieve using easy three steps in JAVA as mentioned in above image.

  1. Locate Root folder using File class.
  2. Get list of all files/folder in File[ ] array using listFiles() method.
  3. Get individual file/folder name one by one using foreach loop and getName() method



Code Example:
import java.io.File;
public class Test {

	public static void main(String[] args) 
	{
		// Step 1: Locate the root folder.
		File files=new File("C:\\Users\\ashok.kumar\\Downloads\\demoFolder");
		
		// Step 2: Get list of all files/folder in File array.
		File[] fileList=files.listFiles();
		
		int dirCounter=0;
		int fileCounter=0;
		
		System.out.println("List of Files under Root folder:-");
		for (File file : fileList) 
		{
			if(file.isFile())
			{
				// Step 3: Traversing each file one by one.
				System.out.println(file.getName());
				fileCounter++;
			}
		}
		System.out.println("Total Files: "+fileCounter);
		
		System.out.println("\nList of Directories under Root folder:-");
		for (File file : fileList)
		{
			if(file.isDirectory())
			{
				// Step 3: Traversing each folder one by one.
				System.out.println(file.getName());
				dirCounter++;
			}
		}
		System.out.println("Total Directories: "+dirCounter);
	}
}
Output:
List of Files under Root folder:-
Almirah.xlsx
file1.xlsx
file2.xlsx
file3.xlsx
powerpoints checkpoint.xlsx
test case.xlsx
test plan.xlsx
test.docx
Total Files: 8
List of Directories under Root folder:-
Folder_A
Folder_B
Folder_C
Total Directories: 3

Related Links:

OOPs Concept:

OOPs Concept:

Java Question And Answer:


Code Example 2

In this example we are traversing inside each folder and list out all the files inside it.

import java.io.File;
public class SubFolderTraverse {

	public static void main(String[] args) 
	{
		String rootDir="C:\\Users\\ashok.kumar\\Downloads\\demoFolder";
		
		File[] listFiles=getFileList(rootDir);
		
		for (File file : listFiles) 
		{
			if(file.isDirectory())
			{
				String curDir=file.getName();
				File[] subFolders=getFileList(rootDir+"\\"+curDir);
				System.out.println("\nFiles/folders in current Directory: "+curDir);
				for (File file2 : subFolders) {
					System.out.println(file2.getName());
				}
			}
		}	

	}
	
	public static File[] getFileList(String path)
	{
		File files=new File(path);
		
		 return files.listFiles();
	}

}

Output:
Files/folders in current Directory: Folder_A
blogs.xlsx
filehandling.xlsx
test plan.xlsx

Files/folders in current Directory: Folder_B
Assets.xlsx
Images.xlsx
Slides.xlsx

Files/folders in current Directory: Folder_C
Desktop.xlsx
documents.xlsx
Downloads.xlsx
Folder_D



Search file using a keyword

We can also search any file in folder/subfolders using this method. This example helps to search any file in folder and subfolders at each level. Also, it helps us to find out the multiple/duplicate instances with same name(if any) along with the folder structure. 

In the below example, we have to search all files which contains string “test” in file names. Whether it is in root folder or subfolder at any level. We have three documents as mentioned here in our root folder and sub folders which needs to be find and list out the same on console.

  • Test.docx
  • test plan.xlsx
  • test case.xlsx
Code Example:
import java.io.File;
import java.io.IOException;

public class SearchFile 
{
	/**
	 * @author ashok.kumar
	 * This example helps to search any file in folder and subfolders at each level.
	 * Also, it helps us to find out the multiple instances with same name(if any) along with the folder structure.
	 */
	public static void main(String[] args) throws IOException
	{
		// Step #1: Locate root folder on drive.
		String targetDir="C:\\Users\\ashok.kumar\\Downloads\\demoFolder";
		
		// Step #2: Define search key in a String variable
		String searchKey="test";
		
		// Step 3: Get list of all files and folders in root Directory.
		File[] fileList=getAllFiles(targetDir);
		
		// Step 4: Search keyword in all foders/subfolders.
		searchFile(targetDir,fileList, searchKey);
		
	}
	
	public static File[] getAllFiles(String path)
	{
		File files=new File(path);
		
		 return files.listFiles();
	}
	
	public static void searchFile(String targetDir,File[] fileList,String searchKey)
	{
		
		for (File file : fileList) 
		{
			// First of all search keyword in the root folder.
			if(file.isFile() && file.getName().contains(searchKey))
			{
				System.out.println(file.getName()+" || "+file.getParent());
				
			}
			// Else search the same keyword in subfolders at each level.
			else if(file.isDirectory())
			{
				String curDir=file.getName();
				String newPath=targetDir+"\\"+curDir;
				File[] subfolders=getAllFiles(newPath);
				
				searchFile(newPath, subfolders, searchKey);
			}
		}		
	}
}
Output:
test plan.xlsx || C:\Users\ashok.kumar\Downloads\demoFolder\Folder_A
test plan.xlsx || C:\Users\ashok.kumar\Downloads\demoFolder\Folder_C\Folder_D\Folder E
test plan.xlsx || C:\Users\ashok.kumar\Downloads\demoFolder\Folder_C\Folder_D
test case.xlsx || C:\Users\ashok.kumar\Downloads\demoFolder
test plan.xlsx || C:\Users\ashok.kumar\Downloads\demoFolder
test.docx || C:\Users\ashok.kumar\Downloads\demoFolder

3121total visits,5visits today

Leave a Reply

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

Site Statistics

  • Users online: 0 
  • Visitors today : 7
  • Page views today : 7
  • Total visitors : 48,203
  • Total page view: 66,349

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.