hello, am making a game where you can create and load levels, i couldn't find a way how to embed the level files (txt) into the exported jar (if anyone knows how it would be better i think) but for now in order to play the game the level should be in "C:\JavaGame" what i want is how to load them depending on the folder where the Jar exists for example if your jar is in "C:\Game" then the game will look into "C:\Game\JavaGame" i hope i explained wellthank you

"It's not at all important to get it right the first time. It's vitally important to get it right the last time."

I've found that System.getProperty("user.dir") returns the home directory on Ubuntu (so if your jar is in /home/sam/Documents/PixelZombies/ it will return /home/sam/) unless you go to Terminal and cd to the desired directory and then run the jar via the Terminal. So if you right click the JAR and click "Run in OpenJDK Runtime" (I believe that is what it is, but I'm not on Ubuntu right now) it will not return the right value. This could actually just be an OpenJDK error, but if it isn't, is there a better way to get the same result?

You guys are misinterpreting what the user.dir property is meant to represent. It is the current working directory, not the directory where the program resides. For example, if you run a command in the shell (eg. ls) you want it to list the files in the working directory, not the directory where the ls command resides. If anything's quirky it's probably Windows Java behaviour here.

One way to answer the OP's question may be to use

SomeClass.class.getProtectionDomain().getCodeSource().getLocation()

. Obviously SomeClass should be a class in the JAR you're looking for.

It's usually safe to assume the jar will be launched from the directory it is in....Is there a way to fix this or do we have to stop relying on user.dir?

To assume makes an ass of u and me!

Don't assume that the JAR is launched from the directory it is in. That assumption will break in interesting ways. If your program relies on the directory its JAR is in and not the directory the user is in, don't use user.dir - there's a clue in the name!

Then you should just rely on getClass().getClassLoader().getResource<AsStream>(String). That's the best option as it loads relative to the root of the JAR. If you want to load relative to the Class returned by getClass(), then drop the "getClassLoader()" call to make it getClass().getResource<AsStream>(String).

Note the <AsStream> denotes that it's optional as there are 2 methods: getResource(String) which returns URL and getResourceAsStream(String) which returns an InputStream.

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