'How can I output a random image when in a jar file?

The below code works when running from my editor but the image fails to load when compiled into a runnable jar file with eclipse.

    public static BufferedImage getRandomImage() {
        // returns a random image from the Images folder
        Random rand = new Random();
        URL res = Card.class.getResource("Images"); // located in /src/.../Images
        File f = new File(res.getFile());
        
        if (!f.exists()) {
            return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        }
        File[] files = f.listFiles();
        int random = rand.nextInt(files.length);
        BufferedImage img = null;
        try {
            img = ImageIO.read(files[random]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return img;
    }

Could someone please suggest how I can modify my code or editor to load the files when compiled.

I have read other methods of accessing files but since I need to select randomly from a folder, I need to use the File class.



Solution 1:[1]

The problem is that you are trying to access a URL of a resource as a file.

with this you can get all the images, and then you can do this:

List<String> arr = getResourceFiles("Images");
String imgPath = arr.get(rand.nextInt(arr.size()));
InputStream stream = Card.class.getResourceAsStream("Images/" + imgPath);
try {
    img = ImageIO.read(stream);
} catch (IOException e) {
    e.printStackTrace();
}
return img;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1