This isn't really possible in any nice and clean way.
It would be nice to be able to do .getClass().getResources("/pictures/*.jpg")
(or something), but we can't.
The best you can do is cheat a little. If you know the name of the jar file where the images are stored, you can use either the JarFile
or ZipFile
APIs to get a listing:
ZipFile zipFile = null;
try {
zipFile = new ZipFile(new File("...")); // Path to your Jar
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// Here, I've basically looked for the "pictures" folder in the Zip
// You will need to provide the appropriate value
if (!entry.isDirectory() && entry.getName().startsWith("pictures")) {
// Basically, from here you should have the full name of the
// image. You should be able to then construct a resource path
// to the image to load it...
// URL url = getClass().getResource("/" + entry.getName());
System.out.println(entry.getName());
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
zipFile.close();
} catch (Exception e) {
}
}
A better solution would be not to embedded these images in your jar, if you don't know their names in advance.
Embedded resources really should be known by name to your application in advance.
As suggested by AndrewThompson, you could generate a list of resources, add this to your Jar file. At runtime, you would load this file and have access to all the resources.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…