简体   繁体   中英

Java how to load resource in exported jar using URL

I need to load a resource using a URL in a exported jar. So far I've tried this:

private Sound loadSound(String path) {
    URL url = GameSound.class.getClassLoader().getResource(path);
    Sound s = TinySound.loadSound(url);
    return s;
}

But the URL doesn't work after I export the jar. I have put my files that I need to be loaded into the src folder of my project. How can I do this?

The getClass().getResource(path) can use an absolute path of the form "/....". The ClassLoader.getResource(path) uses an absolute path without a leading slash: "xyz/abc/uvw`.

The other problem is using the classloader responsible for that jar. Your GameSound should best reside in the same external jar.`.


Problem: in src it works in a jar not:

When having just one jar, check with 7zip or WinZip the file path in the jar. Especially paths in jars and on non-Windows systems are case-sensitive .

For /a/b/c/d.png one can use:

a.b.MyClass.getResource("c/d.png");
e.f.MyClass.getResource("/a/b/c/d.png");

Where MyClass resides in the same jar.

The second cause might be that the using class internally expects a file:// or http:// URL. That would simply be utterly bad API design.

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