Listing Files and Directories
Home ] Up ] The File Class ] [ Listing Files and Directories ] Listing with Filtration ]

 

 

When an instance of File represents a directory, the list() methods:

  • list()
  • list(FilenameFilter filter)

may be used to obtain lists of files in that directory. Here's an example:

package inputOutput;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;

/**
 *  This class finds the current directory, gets a list of all
 *  the files/directories in the current directory, separates
 *  the files from the directories, and prints out the two lists.
 */
public class DirectoryLister
{
    public static void main(String[] args)
    {
        // Get current directory
        File dir = new File( System.getProperty("user.dir") );
        // Print out its contents
        printDirectoryContents(dir);
    }
    
    public static void printDirectoryContents(File dir)
    {
        if (!dir.isDirectory())
            return;
            
        try
        {
            System.out.println("Directory : '" + 
                                dir.getCanonicalPath() + "'");
            // Get the list of directory contents
            String[] contents = dir.list();
            // Go through the contents, separating out the files vs dirs.
            ArrayList<String> dirs  = new ArrayList<String>();
            ArrayList<String> files = new ArrayList<String>();
            for (int i = 0; i < contents.length; i++)
            {
                File file = new File(contents[i]);
                if (file.isFile())
                    files.add(contents[i]); // Add file name
                else if (file.isDirectory())
                    dirs.add(contents[i]); // Add dir name
            }
            // Print out the list of directories
            System.out.println("Directories:");
            Iterator<String> it = null;
            for (it = dirs.iterator(); it.hasNext(); )
            {
                String name = it.next();
                System.out.println(" " + name);
            }
            // Print out the list of files
            System.out.println("Files:");
            for (it = files.iterator(); it.hasNext(); )
            {
                String name = it.next();
                System.out.println(" " + name);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

When I ran this program directly from within my NetBeans IDE, it gave me the following output:

Directory : '...\NetBeansProjects\InputOutput'
Directories:
 build
 dist
 nbproject
 src
 test
Files:
 .cvsignore
 build.xml
 manifest.mf

As expected, the above program only lists the directories and files in the top level directory.  That is, it does not recurse down into the directory hierarchy.

 

The page was last updated February 19, 2008