简体   繁体   中英

Java how to use an image within a jar file

I was making a game using a JFrame that would load an image to be displayed. Then when I tried to run the program, it didn't find the image in the jar. So, how do you retrieve a file from within a jar? Is it /img.png or img.png or even \\\\img.png ? I just don't know how paths in java work yet.

(Edit) Figured it out.

/img.png is correct. How are you attempting to load it? You need to use a classloader which knows about that JAR file to get at the image file.

Try this method:

http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)

Try something like this, assuming the JAR file is in your classpath.

public class MyClass {
    public static void main(String[] args) {
        InputStream is = MyClass.class.getClassLoader().getResourceAsStream("/img.png");
        // read in the data stream
    }
}

For example,this is the jar file structure

Jar文件结构

Make sure the jar is in the class path, then coding like this

String file01="tom.txt";
String file02="com/paic/jerry.txt";  
InputStream tom=this.getClass().getClassLoader().getResourceAsStream(file01);
InputStream jerry=this.getClass().getClassLoader().getResourceAsStream(file02);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM