×

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

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.