java

How to list contents of a directory in Java

In this tutorial, we are going to see how to list the contents of a directory in Java.

Listing the contents of a directory in Java can be accomplished using the File class. This class provides the listFiles() method which returns a list of objects for a given directory. Objects can represent files or subdirectories. To understand how to browse the contents of a directory in Java, see the following example.
 

How to list contents of a directory in Java
import java.io.*; 
  
public class Main 
{ 
    public static void main(String[] args) throws IOException 
    { 
		  File dir  = new File("C:\\Users\\PC\\Desktop\\Dossier");
		  File[] liste = dir.listFiles();
		  for(File item : liste){
			  if(item.isFile())
			  { 
			  	System.out.format("File name: %s%n", item.getName()); 
			  } 
			  else if(item.isDirectory())
			  {
				  System.out.format("Directory name: %s%n", item.getName()); 
			  } 
		  }
    } 
}

Output:

File name: myFile.pdf
File name: pic.jpg
Directory name: Documents
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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