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:
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
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.