Andrew Thompson said:
Paul said:
InputStream is = MyClass.class.getResourcesAsStream( "foo" );
But what I want to do now is to get the directory that resource
is in because I want to scan that directory for all the
resources in it, not just foo.
URL urlToFoo = MyClass.class.getResource("foo");
File fooFile = new File( urlToFoo.toURI() );
File fooDir = fooFile.getParentFile();
File[] allFooDirFiles = fooDir.listFiles();
...
But there doesn't seem to be an obvious way to do this.
You cannot do 'file lists' on URL's, and there is no
way to determine all resources available to a classpath.
What do you mean by that?
A few lines of code will tell you the names of all of the files in your
classpath. Once you know the names of those files, which are typically jars,
you can easily open each jar and get information on what files are in the
jar. You can, of course, also open those files and use them for whatever you
want.
Here's the code I use:
------------
/*
* Determine the current classpath. The classpath includes, among other
things, the
* names of all jars that are on the classpath.
*/
String classPath = System.getProperty("java.class.path");
/*
* Tokenize the classpath. Examine each directory and file until the
desired jar is found.
* If the jar is found, get a JarFile reference to it, then break out of
the while loop.
*/
StringTokenizer stringTokenizer = new StringTokenizer(classPath,
System.getProperty("path.separator"));
String token = null;
File file = null;
while (stringTokenizer.hasMoreTokens()) {
token = stringTokenizer.nextToken();
/* Get a file reference to the path or file in the token. */
file = new File(token);
/* Skip directories. */
if (file.isDirectory())
continue;
/* Do whatever you want with the file. If it is a jar, you could
determine what files are in it, or whatever. */
String fileName = file.getName();
if (DEBUG) System.out.println("File name is: " + fileName);
break;
}
catch(Exception excp) {
//error handling }
} else {
continue;
}
} //end while