Java Program to Display all the Directories in a Directory
Last Updated :
28 Jan, 2022
The directory is the organizing structure of the computer file system which is not only responsible for storing files but also to locate them on the memory. File organization structure is a hierarchical structure involving parent and child relationships just like what is there in tree data structures. It will vary from operating systems, rather the efficiency of the operating system is measured with the ease of file organization structure for the end-users.
The following classes in Java are present there to list directory content
- java.nio.file.Files
- org.apache.commons.io.FileUtils
- java.io.File
The hierarchical structure of Directory
Prerequisite: File And Directory Commands
- Terminal Command used to compile any java code on the machine
- Terminal Command used to Run any java code on the machine
java class_name.java // For Compilation
java class_name // For Execution
Action |
Command |
To navigate into the root directory |
cd / |
To navigate to your home directory |
cd |
To navigate up one directory level |
cd .. |
To navigate to the previous directory |
cd – |
To lookup for files inside the current instance directory |
ls |
Approach: There are two standard approaches in accessing the directory in Java. Discussion over approaches is given below:
Approach 1: listFiles() method to store all files in an array to print all the files present in the current folder.
Here is the implementation for the same.
Java
import java.io.*;
import java.io.File;
class GFG {
public static void main(String[] args)
{
File currentDir = new File( "." );
displayDirectory(currentDir);
}
public static void displayDirectory(File dir)
{
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println(
"directory:"
+ file.getCanonicalPath());
displayDirectory(file);
}
else {
System.out.println(
" file:"
+ file.getCanonicalPath());
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Output: Terminal displaying all the directories in a directory
Approach 2: Now, here simply the Brute-force attack is taken into consideration that is to access the given directory and simply printing the directories/file present in the specified folder. Here is the implementation for the same.
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
File file = new File( "/Desktop" );
String[] fileList = file.list();
for (String str : fileList) {
System.out.println(str);
}
}
}
|
Output:
This code accesses over network volume.
Note: In the above example we have written the path for Linux user. For Windows users, you have to use double-backslash while specifying the path. It is because the \ character is used as an escape character in Java. Hence, the first backslash is used as an escape character for the second one.
Share your thoughts in the comments
Please Login to comment...