How to Get List of Files in a Directory in Java

Java IO package ( provides class named File which is abstraction of file and directory names. This class provides an abstract, system independent view of path names. The following sample Java program prints a list of files and folders in a specified directory. The program also uses File attributes to indicate whether a directory entry is a file or a directory. Use the isFile() method to distinguish between files and directories.

If you are running this example on a Linux system, replace the rootFolder variable value with an appropriate path such as /home/user/.

Getting List of Files in a Directory in Java


public class FileDemo {

    public static void main(String[] args) {
        String rootFolder = "c:\\";
        File aFile = new File(rootFolder);
        System.out.println("Type      | Name");
        for(File file: aFile.listFiles()) { // Java 5 style for loop
            System.out.print(file.isFile()? "File     ":"Directory");
            System.out.print(" | ");
            System.out.println(file.getName() );

Note that listFiles() method returns everything including hidden files and folders. You can use the isHidden() method to check whether a file or folder is hidden in the file system. You can also use the File class to create directories, rename files/folders or to delete files and folders.

Since Java 7, java.nio.file package provides better handling of file systems and file attributes. If you are supporting Java 7 and above only use this package as it is more reliable.