This Java File IO tutorial guides you how to write code to list content of a directory.

In Java, to query a list of files and directories in a specific directory, we use the File class under java.io package and follow these steps:

    • Create a new File object:

File dir = new File(“C:/Path/To/My/Directory”);

    • Use one of the following methods of the File class:
      1. String[] list()
      2. String[] list(FilenameFilter filter)
      3. File[] listFiles()
      4. File[] listFiles(FileFilter filter)
      5. File[] list(FilenameFilter filter)
There are 5 methods which do the same thing, so when to use which method? Well, the following explanation could you help you how to identify the method you need:

    • If you just want to get names of the files and directories, use the methods that return an array of Strings, the list() methods (method 1 and 2).
    • If you want to get a list of File objects in order to do something with the files, then go with the methods that return an array of File object, the listFiles() methods (method 3, 4 and 5).
    • If you want to list all files and directories in the specified directory, use the no-argument methods (method 1 and 3)
    • If you don’t want to list all files and directories, but some kind of files based on some conditions, then go with the methods that accept a FilenameFilter or FileFilter as an argument (method 2, 4, and 5). Then you have to create a class that implements either the interface FilenameFilter or FileFilter, and override their methods accept(File dir, String name) or accept(File pathname), respectively.
To remember this stuff easily, keep in mind that:

    •          The list() methods return an array of Strings.
    •           The listFiles() methods return an array of File objects.
    •           The non-argument methods list everything under the directory.
    •          The argument-based methods list only files and directories which satisfy the filter you provided.
And next are some code examples.

 

Java Directory Listing Code Example 1:

List all files and directories with names as an array of Strings.

String dirPath = "g:/Music/English";
File dir = new File(dirPath);
String[] files = dir.list();
if (files.length == 0) {
    System.out.println("The directory is empty");
} else {
    for (String aFile : files) {
        System.out.println(aFile);
    }
}

This example uses String[] list() method to get names of files and directories just as Strings, and you can’t do anything further with the files/directories. 

 

Java Directory Listing Code Example 2:

List all files and directories with names as an array of File objects.

String dirPath = "g:/Music/English";
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files.length == 0) {
    System.out.println("The directory is empty");
} else {
    for (File aFile : files) {
        System.out.println(aFile.getName() + " - " + aFile.length());
    }
}

 This example uses File[] listFiles() method to retrieve an array of File objects, so you can do something more with an individual file or directory, such as getting absolute path or file size.

 

Java Directory Listing Code Example 3:



List some files and directories by a filter class that implements FilenameFilter interface.

Suppose we want to list only MP3 files, create a local class that implements the interface FilenameFilter, and overrides the accept(File file, String name) method as follows:

FilenameFilter mp3Filter = new FilenameFilter() {
    public boolean accept(File file, String name) {
        if (name.endsWith(".mp3")) {
            // filters files whose extension is .mp3
            return true;
        } else {
            return false;
        }
    }
}; 

If the accept() method returns true, the file will be listed. Then call the method listFiles(FilenameFilter filter) as follows:

String dirPath = "g:/Music/English";
File dir = new File(dirPath);
File[] files = dir.listFiles(mp3Filter);
if (files.length == 0) {
    System.out.println("There is no MP3 files");
} else {
    for (File aFile : files) {
        System.out.println(aFile.getName() + " - " + aFile.length());
    }
} 
Note: as the name suggests, the FilenameFilter interface is for filtering file names only. If you want to filter other file’s properties such as size or modification time, use the method listFiles(FileFilter filter)

 

Java Directory Listing Code Example 4:

List some files and directories by a filter class that implements FileFilter interface.

 Suppose you want to list only the files whose size is greater than 3MB, create a local class that implements the interface FileFilter, and overrides the accept(File file) method as follows: 

FileFilter sizeFilter = new FileFilter() {
    public boolean accept(File file) {
        if (file.isFile() && file.length() > 3*1024*1024) {
            // filters files whose size greater than 3MB
            return true;
        } else {
            return false;
        }
    }
};
 

Then call the method listFiles(FileFilter filter) as follows: 

String dirPath = "g:/Music/English";
File dir = new File(dirPath);
File[] files = dir.listFiles(sizeFilter);
if (files.length == 0) {
    System.out.println("There is no files bigger than 3MB");
} else {
    for (File aFile : files) {
        System.out.println(aFile.getName() + " - " + aFile.length());
    }
}
You can download a Java program for these examples at the end of this article.

 

Related File IO Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (ListFilesExample.java)ListFilesExample.java[sample program]2 kB

Add comment

   


Comments 

#13nup2020-05-05 09:22
how to list all files and directories of program files and program files(x86) for a quick in antivirus?
Quote
#12Monirullah2020-04-29 16:28
hello sir hope you fine and well.
Question: i have created two css style for my application and i want to change when click on radio button and apply on application but, failed? do you have any solution for changing themes in javafx (FXML)?
Quote
#11gerardo martinez2018-10-22 15:35
hola bien como mejor del rock
Quote
#10Nam2018-06-03 22:14
Quoting Harish:
How about entire drive?

On Windows, you can use the path "C:\\" or "D:\\"
Quote
#9Harish2018-05-31 10:39
How about entire drive?
Quote