Write a program to List out files and directories in the specified directory or folder in Java
In Java, file handling is a crucial subject. In your interview, you’ll be asked numerous questions about this subject. I have addressed some of the file handling interview questions, such as how to compare two text files, how to set file permissions, how to append text to a file, how to count characters, words, and lines in a text file, and how to determine the most repeated words in a text file. More file management software is available here. From there, we’ll learn in this tutorial how to use some straightforward examples and java 8 code to list all files in a directory in java. In this blog, we are going to learn about file operations in Java to List out all files and directories in a folder.
Lets say I have a folder with the different files as shown in the below image and I want to List the files present in the folder.
List of all files and directories
import java.io.File;
public class BehindJavaFileOps {
public static void main(String[] args) {
// Creating a File object for directory
File directoryPath = new File("E:\\Studies\\2 semester\\273 Hack Tricks");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
System.out.println("List of files and directories in the specified directory:");
System.out.println(" ");
for (File file : filesList) {
String ss = file.getName();
System.out.println(ss);
}
}
}
Output:
List of files and directories in the specified directory:
10 reasons why PCs crash U must Know.txt
10 Security Enhancements.txt
20 Great Google Secrets.txt
250 Tech books online.txt
36 Graphics & Design Ebooks.txt