English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive List of Java Examples
In this tutorial, we will learn to list all files and subdirectories existing in the directory.
Java fileThe list() method of the class lists all files and subdirectories existing in the directory. It returns all files and directories in the form of a string array.
import java.io.File; class Main { public static void main(String[] args) { //Create a file object File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method"); //Returns an array of all files String[] fileList = file.list(); for(String str : fileList) { System.out.println(str); } } }
Output Result
.vscode file.txt directory newFile.txt
In the above example, we created a file object named file. This object saves information about the specified path.
File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");
We have used the list() method to list all the files and subdirectories existing in the specified path.
file.list();
Note: We useddouble backslash. This is because theCharacterIn Java, \ is used asEscape CharactersTherefore, the first backslash is used as an escape character for the second one.