Get File from Main.class.getResource()

totokaka picture totokaka · Dec 18, 2011 · Viewed 8.2k times · Source

I am making a small game in Java. For this game I just added sounds. So I want to have all my images and audio files in the jar. For pictures this was easy:

new ImageIcon(Main.class.getResource("images/machgd2.png")).getImage()

But for audio it only works when I run the program in Eclipse but not from a jar. I use:

File soundFile = new File(Main.class.getResource(filename).getFile());

So how can I get this file from inside the .jar file?

Update:

OK, got it working, thanks to Andrew! To play the sound I used a class I found on the net, and I found out that class just uses File to get an AudioInputStream, so I dropped the File thing.

Answer

Jon Skeet picture Jon Skeet · Dec 18, 2011

When it's in a jar file, it isn't a file on the file system, is it? You'll either have to copy the file out of the jar file into some temporary location, or use APIs which don't require a file (e.g. ones which only need an InputStream or a URL, both of which are easily available from jar files using getResourceAsStream or getResource.).

You haven't shown where you're using soundFile - if you show us which APIs you're trying to use, we can try to suggest an appropriate alternative.