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
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
javac class_name.java // For Compilation java class_name // For Execution
|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.
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.
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.
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.