Link to home
Start Free TrialLog in
Avatar of dds110
dds110

asked on

Read filenames from a directory

How would I read the filenames in a directory...for that matter, how would I read the directory names as well?  I'm a newbie to java.  I don't need to use the file dialog controls, I need this to be dynamic (i think that's the word i'm looking for).

Let me know if I need to be clearer.

TIA
DDS
Avatar of sct75
sct75

You could ask user to enter in the directory name from the command line or any GUI widget, such as TextField, etc., from a graphical interface.

By obtaining such input, you could do following
java.io.File file = new java.io.File(userInput);

The file.isDirectory() will tell if the user input represents a directory.

The the file.list() will return you a String[] that contains the files and directories in the directory, including the "." (self) and ".." (the parent). Or the file.listFiles() returns you an array of abstract pathnames denoting the files in the directory.
ASKER CERTIFIED SOLUTION
Avatar of yongsing
yongsing

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of girionis
 The following reads all the files into a directory and directories within directories:

import java.util.*;

public class GetAllFilesInADirectory
{
     private static Vector v = new Vector();
     
     public static void main(String [] arguments)
     {
          Vector vec = getAllFiles(new java.io.File("c:/ColumbusXMLFiles"));
     
          for (int i=0; i<vec.size(); i++)
          {
               System.out.println(vec.elementAt(i));
          }
     }
     
     public static Vector getAllFiles(java.io.File location)
     {
          java.io.File [] list = location.listFiles();
         
          for (int i=0; i < list.length; i++)
          {
               v.addElement(list[i]);

               if ((list[i]).isDirectory())
               {
                    getAllFiles(list[i]);
               }
          }
         
          return v;
     }
}
 Just change this bit: "c:/ColumbusXMLFiles" with your own directory name.
Mistake in my code. First line should be:

File file = new File("C:/temp");

or

File file = new File("C:\\temp");