olta8 olta8 - 2 years ago 98
Java Question

Java Load From Reasource In Jar

I am having some difficulty loading files from resources in eclipse. In the IDE, loading works fine. In a compiled jar everything breaks.

This works for loading an image inside and outside of a jar:


This works only in the IDE for a file object (I know it's messy):

File f = new File(Thread.currentThread().getContextClassLoader().getResource("Overworld.mp3").getPath().replace("%20", " "));

I was hoping that there was a constructor for a file object File(InputStream) so I could use the first method of loading an image (which works flawlessly so far) for a file. This, however doesn't exist.

Is there any other method of loading a file into a file object in such a way that it works in the IDE and in a compiled jar?

Thanks in advance.

(Separate but related question: why does
File f = new File(this.getClass().getResource("Overworld.mp3").getFile());
give a MEDIA_UNAVAILABLE exception? The file is in the same package as "E.png" with all other source files in my project)

ck1 ck1
Answer Source

getResourceAsStream() returns a java.io.InputStream that you can use to read the contents of a resource in a jar as a byte array.

Will this work for you?

Why do you require a java.io.File?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download