Monday, 12 September 2011

Directory and File Listing Example in Java

This example illustrates how to list files and folders present in the specified directory. This topic is related to the I/O (input/output) of package.
In this example we are using File class of package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
  1. An optional system-dependent prefix string,
    such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
  2. A sequence of zero or more string names.
This program list the file of the specified directory. We will be declaring a function called dirlist which lists the contents present in the specified directory.
dirlist(String fname)
The function dirlist(String fname) takes directory name as parameter. The function creates a new File instance for the directory name passed as parameter
File dir = new File(fname); 
and retrieves the list of all the files and folders present in the directory by calling list() method on it.
String[] chld = dir.list();  
Then it prints the name of files and folders present in the directory.
Code of the Program :

public class  DirListing{
  private static void dirlist(String fname){
  File dir = new File(fname);
    String[] chld = dir.list();
  if(chld == null){
  System.out.println("Specified directory does not exist or is not a directory.");
  for(int i = 0; i < chld.length; i++){
  String fileName = chld[i];
  public static void main(String[] args){
  case 0: System.out.println("Directory has not mentioned.");
  case 1: dirlist(args[0]);
  default : System.out.println("Multiple files are not allow.");
Download Directry Listing Example
Post a Comment