List Contents Of Directory In Java

In today’s post you will learn list contents of directory in java.

The easiest way of doing is using the class File which offers list() method which in turn returns String-array. Here i’m using string array files to hold all the names of contents in directory. Let’s see code implementation,

example: List Contents Of Directory In Java

List Contents Of Directory In Java

Also Read – Create Directory Java Program

import java.io.*;

public class List_Contents_Of_Directory_In_Java {

public static void main(String[] args) {

File fl = new File("A://Workspace");
String files[] = fl.list();
System.out.println("List of Contents of " + fl.getPath());
for(int x = 0;x < files.length;x++)
{
System.out.println(files[x]);
}
}
}

Output:

List of Contents of A:\Workspace
demo.javaclass
demo.flowerbrackets

For example i’m listing all the files in the A drive using java code. Further i have created List_Contents_Of_Directory_In_Java class. First we have to create file object ‘fl’ to a new file and inside the braces we have to mention path. In the next step we want to print all the files of the A drive. To do this we have a method in java called fl.list(),

String files[] = fl.list();

fl.list() will return a string array. Now we will loop through all these string array to get the names of files located in A drive. So i have written a for loop which will print all the above files.

So this is how we list all the files in a particular folder using java code.

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *