codescracker


java

Java Program to List Files in Directory



« Previous Program Next Program »


List all Files in Current Directory

To list and display all files present in the current directory in Java programming, you have to first import the two package, java.util.* and java.io.*, here * indicates that we are importing all the classes (in short, importing the whole java.util package) present in these package and then start listing and printing all the files present in the current directory as shown in the following program.

Java Programming Code to List Files in Current Directory

Following Java program list all the files present in the current directory :

/* Java Program Example - List All Files in Current Directory */
		
import java.util.*;
import java.io.*;

public class JavaProgram
{
    public static void main(String args[])
    { 
        if(args.length == 0)
        { 
            args = new String[] { ".." }; 
        }

        List<String> nextDir = new ArrayList<String>(); 
        nextDir.add(args[0]);
        try
        { 
            while(nextDir.size() > 0)
            {     
                File pathName = new File(nextDir.get(0)); // gets the element at the index of List 
                String[] fileNames = pathName.list();     // lists all the files in the directory
                for(int i = 0; i < fileNames.length; i++)
                { 
                  File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String, 
                                                                       // constructor creates a new File object with fileName name   
                  if (f.isDirectory())
                  { 
                     System.out.println(f.getCanonicalPath()); 
                     nextDir.add(f.getPath()); 
                  } 
                  else
                  {
                      System.out.println(f);
                  }
               } 
               nextDir.remove(0); 
            } 
        } 
        catch(IOException e)
        { 
            e.printStackTrace();  
        }       
    } 
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program list files in directory

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test