views:

54

answers:

3

When my program starts to run, how do I list available java source file names ? For example, I have a few dozen source files named "My_App_*.java" in my src directory, after I start my app, how can I call Java to list source files start with "My_App_" dynamically ?

Frank

A: 

Use java.io.File.list and its related methods. You can either get a String[] of filenames, or File[]. You can provide a FilenameFilter or a FileFilter, or you can filter the returned array afterward.

polygenelubricants
+2  A: 
new File(".").list(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
    return name.startsWith("My_App_") && name.endsWith(".java");
  }
});

Replace . with the directory where the files are.

But why do you need to do that?

Matthew Flaschen
+1 for asking why.
Yishai
Why ? Because my program dynamically generated some java source files, and at the time of programming, I don't know what they might be called besides the prefix.
Frank
+1  A: 

If you know where the source directory is:

File srcFolder = new File("./src");
String[] files = srcFolder.list();
for(String file : files){
    if(file.startsWith("My_App_")){
        System.out.println(file);
    }
}
Brendan Long