Jacob Birkett
Jacob Birkett

Reputation: 2125

Load resources in Java from absolute path within jar

Don't flag as duplicate yet!

Hear me out; all of the solutions that I have seen are good, but I don't understand how the class paths work when loading resources using:

ClassLoader classLoader = getClass().getClassLoader()

I want to set up a resource loader (named ResourceLoader) that can load from anywhere within the jar package.

So if the loader is placed in com.spikespaz.engine.loader.ResourceLoader, I don't want to be stuck in the relative path of com.spikespaz.engine.loader.

I want to be able to load from com.spikespaz.game.resources.textures and com.spikespaz.game.resources.models without the need to put a reader in the parent directory.

What I found is this: https://stackoverflow.com/a/3862115/2512078

But from what I understood, all of those options in his answer must be relative to the class loading them. (getClass()) Is there a way around this, or am I misunderstanding it?

If I am misunderstanding it, could someone explain better?

Any solutions must be relative to the exact root of the jar package or source of the development environment, and I must not need to put anything in that root.

Thanks.

Upvotes: 1

Views: 2074

Answers (1)

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

I think you misunderstood or misread his answer https://stackoverflow.com/a/3862115/2512078

Both the normal classloader and the context classloader are able to load resources with an absolute path.

To do this using the normal classloader, make sure the resource path has a leading / in front of it, otherwise it loads the resource relative to the package of the class loading it.

this.getClass().getResource("/foo/bar.txt")` 

The context classloader is never loading resources relative to a class, paths are always interpreted as absolute paths.

Thread.currentThread().getContextClassLoader().getResource("foo/bar.txt")

Note: Do not use a leading slash with the context classloader.

Upvotes: 2

Related Questions