Related Articles

Related Articles

Java Program to Traverse in a Directory
  • Last Updated : 22 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to trverse through a directory
import java.io.File;
  
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
                // recursivly to list files present
                // in sub directory
                displayFiles(filename.listFiles());
             }
            
            // print the file name present in given path
            else 
            {
                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
        displayFiles(files);
    }
}

chevron_right


Output:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to display files with 
// complete path present in a directory
  
import java.io.*;
  
// Importing Files
import java.nio.file.*;
import java.util.stream.Stream;
  
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
            filepath.forEach(System.out::println);
        }
        
        // if no such directory exists throw an exception.
        catch (IOException e) 
        {
            throw new IOException("Directory Not Present!");
        }
    }
}

chevron_right


Output:

c:\GFG
c:\GFG\article.docx
c:\GFG\GFG.txt
c:\GFG\numbers.txt
c:\GFG\Ritik
c:\GFG\Ritik\Logistics.xlsx
c:\GFG\Rohan
c:\GFG\Rohan\Payments.xlsx

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :