Home »
Java Programs »
Core Java Example Programs
Java program to get list of files, directories from a directory
Get list of files, directories from a directory - This program will print the name of files and directories which are available in a given directory.
To get the list of files we will use File.listFiles(), this method will return the name of all files and directories, and then we will check that item is a file or directory by using File.isFile() and File.isDirectory().
Get list of files, directories from a directory using Java program
import java.io.File;
class GetFilesFromDirectory {
public static void main(String[] args) {
File dirName = new File("D:/eclipse");
File[] listFiles = dirName.listFiles();
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i].isFile()) {
System.out.println("File: " + listFiles[i].getName());
} else if (listFiles[i].isDirectory()) {
System.out.println("Directory: " + listFiles[i].getName());
}
}
}
}
Output
File: .eclipseproduct
File: artifacts.xml
Directory: configuration
Directory: dropins
File: eclipse.exe
File: eclipse.ini
File: eclipsec.exe
File: epl-v10.html
Directory: features
File: notice.html
Directory: p2
Directory: plugins
Directory: readme
Core Java Example Programs »