Helping Information

Java Program to List Files in a Directory

Java Program to List Files in a Directory

Problem Definition: Write a Java Program to List Files in a Directory.

In this post, we will discover how to list all the files and sub-directories present inside a directory.

on the positive view if you don’t have the latest version of Java click here.

The “list()” method of the Java File class is applied to list all the files and sub-directories present inside a directory. It delivers all the files and directories as a string array.

What is Directory?

A directory or file is used to store, classify and separate files and directories on a system. Let’s see, if you have a huge number of files having different types. You could have a directory to store them and likewise create a different directory for storing files. Usually, we are creating directories for a different type like music, video and documents. You could easily navigate through the files.

Example: Java Program to List Files in a Directory using list() method

import java.io.File;

class Main {

     public static void main(String[] args) {

     // creates 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

Java Program to List Files in a Directory
Output of Java Program to List Files in a Directory

As Shown earlier example, we have created a file object name given as file. The object contains information about the specific path.

File file = new File(“C:\Users\Guest User\Desktop\Java File\List Method”);

We have using the “list()” method to list all the files and sub-directories present in the specific path.

file.list();

Note: We have to use double-backslash while defining the path. It is due to the character is used as an escape character in Java. Accordingly, the first backslash is used as an escape character for the second one.

With this program, you will simply be list sub-directories. As well as, you will able to list all files. This supports you with a different path. But, the file path should be correct.

Related Post:

  1. Java Program to Copy File
  2. Java Program to Rename File
  3. Java Program to Create Directories
  4. Java Program to Find ASCII Value of a character.

1 comment / Add your comment below

Leave a Reply

Your email address will not be published. Required fields are marked *