How to Get List of Files from Directory in Java

Get List of Files from Directory in Java

In this simple example, We will show you about how to get list of files from directory in Java. The example was tested and output shared in the post.

#1 Get all file names from directory

package com.dineshkrish.io;

import java.io.File;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class FileListExample1 {

	public static void displayFileNames(String path) {

		if (path != null && !path.isEmpty()) {

			// defining File Object for Directory
			File fileDirectory = new File(path);

			// getting all file name from directory given
			String[] fileNames = fileDirectory.list();

			// validating and populating the array 
			if (fileNames != null && fileNames.length > 0) {

				for (int i = 0; i < fileNames.length; i++) {

					// printing file name
					System.out.println(fileNames[i]);
				}

			}
		} else {
			
			// print some error message here..
		}
	}

	public static void main(String[] args) {

		// the path or directory, which you can change accordingly.
		String path = "C:/Users/dineshk/Desktop/my_directory";

		// calling the method
		FileListExample1.displayFileNames(path);
	}
}

Output

a.txt
b.txt
c.txt
d.txt
e.txt
f.txt
g.txt
h.txt
i.txt

#2 Get all file as objects from directory

package com.dineshkrish.io;

import java.io.File;

/**
 * 
 * @author Dinesh Krishnan
 * 
 */

public class FileListExample2 {

	public static File[] getFiles(String path) {

		// defining the file array object
		File[] files = null;

		if (path != null && !path.isEmpty()) {

			// defining file object
			File fileDirectory = new File(path);

			// getting the list of file as object
			files = fileDirectory.listFiles();

		} else {

			// print some error message here..
		}

		// returning the result
		return files;
	}

	public static void main(String[] args) {

		// you can change your path name
		String path = "C:/Users/dineshk/Desktop/my_directory";

		// method calling
		File[] files = FileListExample2.getFiles(path);

		// validating and populating the result
		if (files != null && files.length > 0) {

			for (File temp : files) {

				// do something here

				System.out.println(temp);

			}
		} else {

			// print some error message here..
		}

	}

}

Output

C:\Users\dineshk\Desktop\my_directory\a.txt
C:\Users\dineshk\Desktop\my_directory\b.txt
C:\Users\dineshk\Desktop\my_directory\c.txt
C:\Users\dineshk\Desktop\my_directory\d.txt
C:\Users\dineshk\Desktop\my_directory\e.txt
C:\Users\dineshk\Desktop\my_directory\f.txt
C:\Users\dineshk\Desktop\my_directory\g.txt
C:\Users\dineshk\Desktop\my_directory\h.txt
C:\Users\dineshk\Desktop\my_directory\i.txt

#3 Given directory files screen shot

How to Get List of Files from Directory in Java

References

1. Java File JavaDocs
2. java.io.File.list() method
3. java.io.File.listFiles() method