Print Names of all Files in a Folder in Java




java.io.File contains listFiles() method which Returns an array of abstract pathnames denoting the files in the directory. listFiles() can be used to get File object array of files corresponding to each file in a folder.

Syntax of listFiles()

File[] java.io.File.listFiles()

The below demo program demonstrates how to print Names of all Files in a Folder in Java.

package com.masterjavatutorial;

import java.io.File;

public class TestExample {
	
	public static void main(String[] args){
        
		File folder = new File("/srv/KT");
		File[] listFiles = folder.listFiles(); 
		
		for(File file : listFiles){
		   if(file.isDirectory()){
     		      System.out.println("Folder Name : "+ file.getName());
		   }else{
		      System.out.println("File Name : "+ file.getName());
		   }
		}
		 
	}
			
}

Output of the above program is as below:

File Name : QA_Server_Details.txt
File Name : 1.txt
File Name : Tools.txt
Folder Name : AllTasks
File Name : Grunt.txt
File Name : elastic_search.txt
File Name : Node_JS.txt
File Name : hosts
File Name : Pb_url_uploader.txt
Folder Name : Useful_Server_Details
File Name : consumer_app_api.txt
File Name : git_tutorial.txt
Folder Name : daily_code_android_tutorial
File Name : photobook_downloaed_or_shared.txt