How do I get a .giff file from a .jar

How do I get .gif file called red.gif from the package jar file I am using.

At the moment I am getting red.gif from the local directory;

Icon iconRed =new ImageIcon("red.gif");

I need to get the .gif from a guaranteed place, such as the .jar file.

Thanks

Gary

[356 byte] By [GE-Teca] at [2007-11-27 4:00:52]
# 1

The following snippet extract a file (red.gif) from a jar.

import java.io.*;

import java.util.jar.*;

import java.util.zip.*;

public class ExtractFromJAR {

public void extractMyMDBromJAR(String fileName, String dest){

try {

String home = getClass().getProtectionDomain()

.getCodeSource().getLocation()

.getPath().replaceAll("%20", " ");

JarFile jar = new JarFile(home);

ZipEntry entry = jar.getEntry(fileName);

File efile = new File(dest, entry.getName());

InputStream in =

new BufferedInputStream(jar.getInputStream(entry));

OutputStream out =

new BufferedOutputStream(new FileOutputStream(efile));

byte[] buffer = new byte[2048];

for (;;) {

int nBytes = in.read(buffer);

if (nBytes <= 0) break;

out.write(buffer, 0, nBytes);

}

out.flush();

out.close();

in.close();

}

catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String args []){

new ExtractFromJAR().extractFileFromJAR("red.gif", ".");

}

}

Hope That Helps

java_2006a at 2007-7-12 9:05:29 > top of Java-index,Java Essentials,New To Java...
# 2
If the .class file and the image file are in the same "folder" in the jar:URL url = this.getClass().getResource("red.gif");Icon icon = new ImageIcon(url);
DrLaszloJamfa at 2007-7-12 9:05:29 > top of Java-index,Java Essentials,New To Java...
# 3

Thanks for the two solutions. I have used the 2nd solution.

I should of explained myself a bit better. I want to use the .gif, from the .jar, without extracting it.

The 2nd solution is perfect. I will keep the first example for another use I have in mind. I need to be able to extract .properties files, if they are missing from an installation.

Thanks!

Gary

GE-Teca at 2007-7-12 9:05:29 > top of Java-index,Java Essentials,New To Java...
# 4
There is a version of getResource that make be of use to you:InputStream in = this.getClass().getResourceAsStream("something.properties");
DrLaszloJamfa at 2007-7-12 9:05:29 > top of Java-index,Java Essentials,New To Java...