How to use files in Jar file

Hi,

I have one program which displays images on main form.

But when I package all these classes and image files it shows file not found.

I want it should read the image files which are in the same jar file.

How can I use the files which are packaged in a Jar file?

[295 byte] By [student@sunDNa] at [2007-11-27 10:13:48]
# 1

Here's some sample code I stole from another website.

public void readTextFromJar(String s) {

String thisLine;

try {

InputStream is = getClass().getResourceAsStream(s);

BufferedReader br = new BufferedReader

(new InputStreamReader(is));

while ((thisLine = br.readLine()) != null) {

System.out.println(thisLine);

}

}

catch (Exception e) {

e.printStackTrace();

}

}

bschauwejavaa at 2007-7-28 15:29:15 > top of Java-index,Java Essentials,Java Programming...
# 2

If you have your images in a directory called res within your jar then use the following method: -

getClass().getResource("/res/image.gif")

c0demonk3ya at 2007-7-28 15:29:15 > top of Java-index,Java Essentials,Java Programming...
# 3

Man... I've seen this question asked and answered a gazillion times... All you needed to do was a search, through the forum or google...

anyway, if I remember correctly, it's getClass().getClassLoader().getResource(<path to the resource>)

jadespirita at 2007-7-28 15:29:15 > top of Java-index,Java Essentials,Java Programming...
# 4

> anyway, if I remember correctly, it's

> getClass().getClassLoader().getResource(<path to the

> resource>)

You can do it that way but, in general, the only difference from using getClass().getResource is that, if the path doesn't start with the class' package, you need a '/' on the start.

malcolmmca at 2007-7-28 15:29:15 > top of Java-index,Java Essentials,Java Programming...
# 5

yeah, I just realized that from reading

http://forum.java.sun.com/thread.jspa?threadID=626615&messageID=3595279

jadespirita at 2007-7-28 15:29:15 > top of Java-index,Java Essentials,Java Programming...