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
Let me know if I need to be clearer.
TIA
DDS
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:/ColumbusX MLFiles")) ;
for (int i=0; i<vec.size(); i++)
{
System.out.println(vec.ele mentAt(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;
}
}
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:/ColumbusX
for (int i=0; i<vec.size(); i++)
{
System.out.println(vec.ele
}
}
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");
File file = new File("C:/temp");
or
File file = new File("C:\\temp");
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.