Listing files within a directory

No developmental utility kit would be complete without a code snippet that allows applications to examine a file directory. Various circumstances could demand that your applications search for a specific file or post the listings of a directory or two.
 
Below is some sample code that will take a directory listing and print out the names of the contained files:

 
import java.io.File;
 
public class DirectoryListing 
{
   public void showDirectoryFiles 
    {
        File dir = new File("/tmp/files");
        File[] files = dir.listFiles();
 
        for (int i=0; i<files.length; i++)
         {
            // Check to see if file is actually a "file"
            if (files[i].isFile()) 
            {

                System.out.println("File : " + files[i].getName());
            } 
            else if (list[i].isDirectory()) 
            {
                System.out.println("Directory : " + files[i].getName());
            }            
        }
    }
 
 public static void main (String args[])
  {
    DirectoryListing dl = new DirectoryListing();
    dl.showDirectoryFiles();
    }
}

This functionality can be expanded and/or modified to do all kinds of useful searches and such. As always, keep that utility set growing!
Hosted by www.Geocities.ws

1