Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

List Files in Directory Java

Using file.listFiles() method in java.io.File package, you can list files in a directory. See the example below. 

 

package com.seleniummaster.examplefile;

import java.io.File;

public class ListFilesInDirectory {

    public static void main(String[] args)
    {
        ListFiles("testdir");
    }

    public static void ListFiles(String DirectoryName)
    {
        //project directory
        String workingDirectory = System.getProperty("user.dir");
        String  dir = workingDirectory + File.separator + DirectoryName;

        System.out.println("Final file directory : " + dir);

        //List files in the directory

        File file = new File(dir);
        File[] files=file.listFiles();

        if (file.exists()) {
            System.out.println("Directory is found!");
            for(File eachFile: files)
            {
                System.out.println(eachFile.getName());
            }
        } else {
            System.out.println("Directory is not exits");
        }

    }

    }

Run the code and see the result

Final file directory : C:\seleniummaster\testdir
Directory is found!
test1.txt
test2.txt
test3.txt

Process finished with exit code 0