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”.
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.
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.
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.