2

I am trying to display a number of BufferedImage elements stored in an ArrayList<BufferedImage> by first reading them from the disk to the arraylist then iterating across the arraylist. Since the images are organised into subfolders on the filesystem, I read them into the arraylist with

private void storeImages(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            storeImages(fileEntry);// recursively iterates across all
                                    // subdirectories in folder
        } else {
            try {
                imageList.add(ImageIO.read(fileEntry));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

If I use JFileChooser to select a directory on which to call storeImages, then the code works fine. However, I want to package the images into an executable JAR file so that the images don't have to be distributed separately and so users don't have to find the place on disk where the images are stored. To try and read files from within the JAR, I tried

storeImages(new File(getClass().getResource("/images").toString());

but this throws a NullPointerException. If push comes to shove, I can read the images from the filesystem, though I would prefer to read them from the JAR file. What exactly should I do to read the images from the JAR?

Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
Charles German
  • 857
  • 10
  • 16

1 Answers1

2

Unfortunately, your code will not be reusable as-is in the case you want to explore your jar file automatically, because you just cannot create File instances from the contents of a jar file. This is covered in this post: Unable to create File object for a file in Jar

There was also this similar question suggesting a possible solution: How do I list the files inside a JAR file?

Community
  • 1
  • 1
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
  • Thanks! I did not realize the limitations of the `File` class with respect to JAR files. – Charles German May 24 '15 at 19:01
  • 1
    It depends on how much you want to stick with ancient APIs. After all, it doesn’t make much sense complaining about the limitations of an old API when the solution already exists for some years; don’t use `File`, use `Path`. [Here](http://stackoverflow.com/a/28833044/2711488) is an example code which lists classes within a `package` regardless of whether they are stored as files or within an archive. It should be easy to adapt it for listing other kind of files, but note that if you want to read *all* entries of a kind anyway, linearly scanning a zip file is more efficient than recursive scan. – Holger May 26 '15 at 09:20