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