×

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some of the files. Those files are also a part of the main directory. Therefore, we must mention them.

directories without Sub-directories

It denotes a folder's file-only status. The steps which are given below will describe how to print the files

1. create an object for the directory in step one.

2. The second step is to get the directory's arrays of files.

3. Print each file's name (including extension) one at a time in a recursive fashion.

Implementation

The code below outputs the file names found in the Documents folder. The files found in the Documents folder are displayed in the screenshot below.

List All Files in a Directory in Java

DisplayFile.java

//this program is for a list of all the documents in the directory in java
//import section
import java.io.File; 
//The class DisplayFile is created
public class DisplayFile 
{  
public void printNames(File[] array, int i, int lvl)  
{  
//initializing the base condition  
// if the condition i==array.length then there are  
// no more files.The loop will terminate. 
if(i == array.length)  
{  
return;  
}  
// checking whether it is f  file or not
if(array[i].isFile())  
{  
System.out.println(array[i].getName());  
}  
// The files in the directory are printed according to the recursion process  
// the value i+1 means checking the next file in the directory 
printFileNames(array, i + 1, lvl);  
}  
// Main section
public static void main(String[] argvs)  
{  
// the path of the directory
String path = "/Users/mprashanthrao/Documents/My documents";  
//A file object fobject was created  
File fObject= new File(path);  
//   an object obj i created for the class DisplayFile
DisplayFile obj = new DisplayFile();  
if(fObject.exists() && fObjcte.isDirectory())  
{  
// the files in the directory are printed by using the fobject 
File array[] = fObject.listFiles();  
// display the required statements  
System.out.println("-----------------------------------------------------------------------");  
System.out.println("The files in the directory : " + fObject);  
System.out.println("-----------------------------------------------------------------------");  
// the method for calling 
obj.printNames(array, 0, 0);  
}  
}  
}  

Output:

List All Files in a Directory in Java

subdirectory-containing directory

The phrase indicates that a folder has both files and subfolders. The steps will show how to display the directory's files and those of its subdirectories.

  1. Create a File Object for the directory in step one.
  2. The second step is to get the directory's array containing files and subdirectories.
  3. It will show the file name, and the subsequent array[j] element will be reached recursively in step 3 if array[j] is a file.
  4. Repeat step 2 in step 4 if array[j] is indeed a directory and shows the directory name.

DisplayFileEx1.java

// This program is for a list of all  documents in the given document
//import section
import java.io.File;  
public class DisplayFileEx1  
{  
public void printFiles(File[] array, int i, int level)  
{  
//initializing the base condition  
// if the condition i==array.length then there are  
// no more files.The loop will terminate. 
if(i == array.length)  
{  
return;
}  
//files are provided by indentation
for (int j = 0; j < level; j++)  
{  
System.out.print("\t");  
}  
// the condition will checks whether it is the file or not
if(array[i].isFile())  
{  
System.out.println(array[i].getName());  
}  
//reading the files in subdirectories  
else if(array[i].isDirectory())  
{  
System.out.println("[" + array[i].getName() + "]");  z
//the files read until the condition 
printFileNames(array[i].listFiles(), 0, level + 1);  
}  
//The files in the directory are printed according to the recursion process  
// the value i+1 means checking the next file in the directory 
printFileNames(array, i + 1, level);  
}  
// Main section  
public static void main(String[] argvs)  
{  
// Providing the full path for the directory  
String path = "";  
// creating a file object  
File fObject = new File(path);  
// creating an object of the class DisplayFileExample1  
DisplayFileEx1 obj = new DisplayFileEx1();  
if(fObject.exists() && fObject.isDirectory())  
{  
// array contains the files belonging to that directory pointed by fObject 
File array[] = fObject.listFiles();  
// display the required statements  
System.out.println("-----------------------------------------------------------------------");  
System.out.println("The files in the directory : " + fObject);  
System.out.println("-----------------------------------------------------------------------");  
// the method for calling 


obj.printFiles(array, 0, 0);  
}  
}  
}  

Output:

List All Files in a Directory in Java

Related Topics

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.