Java File listFiles() Method
Example
Create a file in a folder, then list the files in the folder:
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File myFolder = new File("myFolder");
myFolder.mkdir();
new File("myFolder/filename.txt").createNewFile();
File[] files = myFolder.listFiles();
for (File f : files) {
System.out.println(f.getName() + " is a file: " + f.isFile());
}
}
}
Definition and Usage
The listFiles() method returns an array of File objects, one for each file and directory in a directory.
Because you get File objects, you can call File methods on each one, like getName() and isFile(). The order of the files is not fixed. If the path is not a directory, the method returns null.
Tip: Use the list() method if you only need the names.
Syntax
One of the following:
public File[] listFiles()
public File[] listFiles(FilenameFilter filter)
public File[] listFiles(FileFilter filter)
Parameter Values
| Parameter | Description |
|---|---|
| filter | Optional. A FilenameFilter or a FileFilter that decides which files to include. Only the files that the filter accepts are put in the array. |
Technical Details
| Returns: | An array of File objects, as a File[]. null if the path is not a directory. |
|---|
Related Pages
❮ File Methods