• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 190
  • Last Modified:

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
0
dds110
Asked:
dds110
  • 2
  • 2
1 Solution
 
sct75Commented:
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.
0
 
yongsingCommented:
The following reads the C:\temp directory, and display the files or directories names.

File file = new File("C://temp");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
    System.out.print(files[i].getName() + " - ");
    if (files[i].isDirectory()) {
        System.out.println("Directory");
    } else {
        System.out.println("File");
    }
}
0
 
girionisCommented:
 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;
     }
}
0
 
girionisCommented:
 Just change this bit: "c:/ColumbusXMLFiles" with your own directory name.
0
 
yongsingCommented:
Mistake in my code. First line should be:

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

or

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

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now