Java - How to list the files in a directory

Java file directory list FAQ: How do I create a list of files in a directory using Java?

Here’s a quick example of a Java class that demonstrates how to create a list of all files in a directory using just the Java File class. Specifically, this example shows how to list all the files in a directory, store those filenames in a String array, and then print the array.

My Java directory “list files” class

Here’s the source code for this “list files in a directory” Java class:

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] );
    }
  }
}

Discussion: Java directory files list example

I won’t get into a detailed discussion of this Java file/directory list example, but I will add a few points here to the comments that are shown in the code:

  • 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.
  • On Unix and Linux systems just specify the directory as normal, i.e., using something like /tmp instead of using the DOS C:/temp directory syntax.
  • If the directory name you specify doesn't really exist, this code will throw a NullPointerException, so you have to be careful of that.
  • I just ran this code against my home directory on a Linux computer, and it does list all the "hidden" files in my home directory. ("Hidden files" are all the filenames that begin with a decimal, i.e., filenames like .bash_profile.)

I can’t think of anything else to add right now, but if you have any questions or comments, just leave them in the comments section below and I'll get back with you.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.