Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Traverse in a Directory

  • Last Updated : 12 May, 2021

A directory is an organizational file system structure that contains Files and Directorates

Here even an attacker can try to traverse or access a folder which we name as ‘File Traversal Attack or Path Traversal Attack a different directory. In short here directory is traversed which is outside the home/root directory. These files are server-internal files that are not accessible by the user.

So let us brief about Traversal Attacks

  • The attacker can access the file from a different directory
  • Directory Browsing is allowed when the server is misconfigured
  • Sometimes even an attacker can access files which are beyond the root directories of the web browser

Prerequisites required are listFiles() and considering there are no path traversal attacks.

There are 2 methods to Traverse in a directory

  • Using listFiles() Method
  • Using Stream<Path>

Suppose there exists a directory with path C:\\GFG. The following image displays the files and directories present inside GFG folder. The sub directory “Ritik” contains a file named “Logistics.xlsx” and sub directory “Rohan” contains a file named “Payments.xlsx”. 

GFG Directory

The following java programs illustrate how to traverse in a directory.

Method 1: Using listFiles() Method

  • Create a File array to store the name and path of files.
  • Call displayFiles method() to display all the files.


// Java Program to traverse through a directory
class GFG {
    // function to display fies
    public static void displayFiles(File[] files)
        // traversing through the files array
        for (File filename : files)
            // if a sub directory is found,
            // print the name of the sub
            // directory
            if (filename.isDirectory())
                System.out.println("Directory: "
                                   + filename.getName());
                // and call the displayFiles function
                // recursively to list files present
                // in sub directory
            // print the file name present in given path
                System.out.println("File: "
                                   + filename.getName());
    // Main Method
    public static void main(String[] args)
        // array to store the name of files and directories
        File[] files = new File("C:\\GFG").listFiles();
        // call displayFiles function to display files


File: article.docx
File: GFG.txt
File: numbers.txt
Directory: Ritik
File: Logistics.xlsx
Directory: Rohan
File: Payments.xlsx

Method 2: Using Stream<Path>

Java 8 onwards, the walk() method was introduced to iterate over the entire directory recursively and retrieves Stream<Path> as the return value.

  • Create a stream of file paths.
  • Print entire directory and file path
  • Throw Exception if no such directory exists as provided in the path.


// Java Program to display files with
// complete path present in a directory
// Importing Files
import java.nio.file.*;
class GFG {
    // Main Method
    public static void main(String[] args)
        throws IOException
        // create try-catch block and provide
        // the directory path
        try (Stream<Path> filepath
             = Files.walk(Paths.get("c:\\GFG")))
           // print the name of directories and files with
           // entire path
        // if no such directory exists throw an exception.
        catch (IOException e)
            throw new IOException("Directory Not Present!");




Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :