0

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.

4

2 回答 2

0

/img.png 是正确的。你是如何尝试加载它的?您需要使用知道该 JAR 文件的类加载器来获取图像文件。

试试这个方法:

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

尝试这样的事情,假设 JAR 文件在你的类路径中。

public class MyClass {
    public static void main(String[] args) {
        InputStream is = MyClass.class.getClassLoader().getResourceAsStream("/img.png");
        // read in the data stream
    }
}
于 2013-03-15T02:20:23.227 回答
0

例如,这是jar文件结构

Jar 文件结构

确保 jar 在类路径中,然后像这样编码

String file01="tom.txt";
String file02="com/paic/jerry.txt";  
InputStream tom=this.getClass().getClassLoader().getResourceAsStream(file01);
InputStream jerry=this.getClass().getClassLoader().getResourceAsStream(file02);
于 2013-03-15T02:21:28.143 回答