English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program lists files in the directory

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.

Example: List all files using the list() method

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.

Comprehensive List of Java Examples