Including Images with an executable jar

Mintybacon picture Mintybacon · Sep 19, 2012 · Viewed 19.5k times · Source

I have been browsing Stackoverflow all day looking for how to do this and I have not been successful yet

I am packaging a quick game I made into a executable jar but I didnt reference the images correctly I just referenced the files

background = ImageIO.read(new File("wood.jpeg"));

I have my classes in src default package Im not sure where I should add the images or if I have to add it to the build path or correct way of adding the images to the build path in the newest version of eclipse

Answer

MadProgrammer picture MadProgrammer · Sep 19, 2012

Files in a Jar are not files in the sense of a file on disk. They are simply a (possibly) compressed stream of bytes.

Java makes it easy to extract these "resources" from Jar files through the use of the ClassLoader

background = ImageIO.read(getClass().getResource("/wood.jpeg"));

Should work...

This will return a URL which ImageIO can use to load the resource.

You could also have a read of

And I could list some more. So, yeah, it gets asked a lot ;)