Reputation: 2185
How would one go about programatically loading all the resource files in a given directory in a JAR file for an applet? The resources will probably change several times over the lifetime of the program so I don't want to hardcode names in.
Normally I would just traverse the directory structure using File.list(), but I get permission issues when trying to do that within an applet. I also looked at using an enumeration with something line ClassLoader.getResources() but it only finds files of the same name within the JAR file.
Essentially what I want to do is (something like) this:
ClassLoader imagesURL = this.getClass().getClassLoader();
MediaTracker tracker = new MediaTracker(this);
Enumeration<URL> images = imagesURL.getResources("resources/images/image*.gif");
while (images.hasMoreElements()){
tracker.add(getImage(images.nextElement(), i);
i++;
}
I know I'm probably missing some obvious function, but I've spent hours searching through tutorials and documentation for a simple way to do this within an unsigned applet.
Upvotes: 1
Views: 1065
Reputation: 10639
You can do it in two ways:
image_1
, image_2
, image_3
), then you can collect all resources you need in one go.Otherwise you need to code a lot. The idea is that you have to:
determine the path to your JAR file:
private static final String ANCHOR_NAME = "some resource you know";
URL location = getClass().getClassLoader().getResource(ANCHOR_NAME);
URL jarLocation;
String protocol = location.getProtocol();
if (protocol.equalsIgnoreCase("jar"))
{
String path = location.getPath();
int index = path.lastIndexOf("!/" + ANCHOR_NAME);
if(index != -1)
jarLocation = new URL(path.substring(0, index));
}
if (protocol.equalsIgnoreCase("file"))
{
String string = location.toString();
int index = string.lastIndexOf(ANCHOR_NAME);
if(index != -1)
jarLocation = new URL(string.substring(0, index));
}
open it as java.util.jar.JarFile
JarFile jarFile = new JarFile(jarLocation);
iterate through all entries and match their name with a given mask
for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();)
{
JarEntry entry = (JarEntry) entries.nextElement();
String entryPath = entry.getName();
if (entryPath.endsWith(".jpg"))
{
// do something with it
}
}
For additional code support, I will refer you to Spring PathMatchingResourcePatternResolver#doFindPathMatchingJarResources().
Upvotes: 1