I asked this question on stackoverflow a while back and got no answer whatsoever. I have a directory called res included in my game which holds my sound and graphics data. I have a completed demo that I'm trying to build into a standalone jar artifact from IntelliJ IDEA. I included the directory in the artifact build, but when I run the standalone jar, it looks for the resources by prepending the entire root directory of my computer to the resource directory. Does anyone know how to fix this??

Here is some example output. Notice how it looks for the resource starting at root on my machine:

I'm going to go out on a limb here and say that I think the answer is that it isn't possible. I think the only way resources can be readable from inside the jar file is if they are somewhere in the classpath. In my case I have resources (maps) that write to disk and are read later, that way the state of the map is persistent when you transition from zone to zone. The problem is that you can't write files to the classpath; they must be in an external directory. However, I probably should move the sound effects to the classpath, since those aren't being written.

You are passing a relative path to File so it's resolving that against the directory you're running the JAR from to get the absolute paths you posted. This is what you're telling it to do! What path are you expecting?

Using relative paths with a JAR is error prone unless you have a launching script (or use the getprotectiondomain().getcodesource().getlocation() workaround) - the path will be wherever you launch the JAR from, not the location of the JAR itself.

If you want to put the resources in the JAR you'll need to switch to getClass().getResource()

Yes, I assumed that this is the problem, because it always is, when people try to include ressources into their artifact In the link I posted is an example how you can make a distinction between "run from the ide" and "run from production-single-artifact-build". Basically it's a configuration based switch that switches between file system loading and the getClass().getResource() idea nsigma mentioned already.

Yes, thank you both; I understand. If you want to access resources that are inside the JAR, they must exist inside the classpath and are accessible using a class loader. You can perform a conditional test to determine whether to use the class loader or access using a relative path. If you try to access internal files using a relative path, the path will resolve to the path where the JAR exists, to inside the JAR, so it's only good for external resources. It's clear now.

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org