How to obtain a list of files in a folder

In this blog post, I will be explaining how you can obtain a list of files in a folder. Consider the following code snippet:

package learnjava.io;import java.io.File;public class FilesInFolderDemo {public static void main(String[] args) {String folderName = "F:/TestFolder";File file = new File(folderName);if (file.exists() && file.isDirectory()) { // check if file exists & is a folderFile[] files = file.listFiles(); //get list of filesif (files.length > 0) {System.out.println("There are " + files.length + " files in the folder");for(int i = 0; i < files.length;i++){System.out.println("File name is "+files[i]);}} else { //empty folder!System.out.println("Folder is empty !");}} else {System.out.println("Folder "+folderName+" is missing or is not a folder");}}}

 

There is a method called File.list on the file interface. If the File object corresponding to the specified path is a directory, then this method will return a list of file names. So the code above will print the following output (assuming there are 2 files test.txt and test2.txt in the TestFolder):

 

There are 2 files in the folderFile name is F:\TestFolder\test.txtFile name is F:\TestFolder\test2.txt

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set