Listing the contents of a directory in Java

Use the File class. Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File []files = new File(args[0]).listFiles();
 
      for (int i=0; i<files.length; i++) {
         // Checks whether this it's a directory
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

If you want to enable wildcards, you can do all the customization yourself using
FilenameFilter. The following example shows you how to list the .java files in
the directory specified at command line:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File path = new File(args[0]);
      File []files = path.listFiles(
               new FilenameFilter() {
                  public boolean accept(File f, String name) {
                     return name.toLowerCase().endsWith(".java");
                  }
               });
 
      for (int i=0; i<files.length; i++) {
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}