Get all images within directory - within jar file

前端 未结 2 601
挽巷
挽巷 2021-01-25 14:07

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:

2条回答
  •  不要未来只要你来
    2021-01-25 15:05

    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 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.

提交回复
热议问题