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

1476total visits,5visits today

Leave a Reply

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