tags:

views:

15

answers:

1

I am looking to access all files in a local directory in a JBoss application. I can put the directory anywhere in my war including WEB-INF if necessary. I then want to access each file in the directory sequentially. In a normal application if the directory was in the run location I could do something like:

File f = new File("myDir");
if(f.isDirectory && f.list().length != 0)
{
    for(String fileName : f.list())
    {
        //do Read-Only stuff with fileName
    }
}

I'm looking for a best-practices solution, so if I'm going about this wrong then please point me to the right way to access an unknown set of resources.

+1  A: 

First thing to note: you're only going to get this to work if you have an exploded WAR, or possibly if the servlet container explodes the WAR for you.

With that caveat in mind, you could use ServletContext.getRealPath() as your starting point. You'd need to know the name of at least one file in the webapp's root directory, and go from there:

String knownFilePath = servletContext.getRealPath("knownFile");
File webAppRootDir = new File(knownFilePath).getParentFile();

// and then as per the question
File f = webAppRootDir ;
if(f.isDirectory && f.list().length != 0)
{
    for(String fileName : f.list())
    {
        //do Read-Only stuff with fileName
    }
}

Getting hold of ServletContext is left as an exercise for the reader.

skaffman
Thanks skaffman, as I've done more research it looks like getting all the files in a folder really isn't practical and that I should be getting it by name using InputStreams (see http://www.coderanch.com/t/89900/JBoss/reading-properties-file).
Adam