How do I create a list of files in a directory?

By Alvin J. Alexander, devdaily.com

For a simple admin servlet that I'm working on, I need to get a listing of files in a directory. In Java this operation takes no more than two lines of code, and I could really squeeze it into one line if I wanted to. But for the sake of clarity, I've broken it up, and even added a little sorting to the directory listing. Hopefully the comments make it self-explanatory.

Here's the source:

import java.io.File;
import java.util.Arrays;

public class DirectoryTestMain
{
  public static void main(String[] args)
  {
    // create a file that is really a directory
    File aDirectory = new File("C:/temp");

    // get a listing of all files in the directory
    String[] filesInDir = aDirectory.list();

    // sort the list of files (optional)
    Arrays.sort(filesInDir);

    // have everything i need, just print it now
    for ( int i=0; i<filesInDir.length; i++ )
    {
      System.out.println( "file: " + filesInDir[i] );
    }
  }
}

This is a complete Java program. Just compile and run this class, and assuming that you have a directory named "C:/temp", you'll be able to get a listing of all the files in that directory.


devdaily logo