Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

java - Get all images within directory - within jar file

I have a folder inside my project that has 238 images. I want to be able to find all images within the directory.

I'm currently accessing all these images like this:

File directory = new File(FileNameGuesser.class.getResource(DIRECTORY).getPath());
for (File file : directory.listFiles()) {
    // filter, process, etc.
}

This works fine within Eclipse. However, when I export to a jar file, FileNameGuesser.class.getResource(DIRECTORY) returns C:Users...file.jar!org... (because it's zipped, I assume) and the method breaks.

How can I achieve this?

EDIT: If possible, I'd like to find a solution that works both in Eclipse and in the jar that's deployed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...