Angstrem
Angstrem

Reputation: 346

How do I set a working directory for Java application?

I've written a simple java app, say, with the following code:

String currentDir = new java.io.File(".").getCanonicalPath();
javax.swing.JOptionPane.showMessageDialog(null, currentDir); //This line shows a graphical dialog with the current dir

When I run it through the terminal, it gives me the directory where the jar-file is located. But when I run it using the GUI file manager (that is, right click on the jar-file -> Open With -> OpenJDK Java 7 Runtime) - the working directory is my user home directory (/home/angstrem). How can I set the working directory to be the one, in which the jar-file is situated?

Upvotes: 1

Views: 905

Answers (2)

user207421
user207421

Reputation: 310913

You can't, and you shouldn't be able to. Consider multi-threading for example. You can only make your application current-path-insensitive.

Upvotes: 0

tom
tom

Reputation: 19153

You can do this:

String jarPath = YourClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();

replacing YourClass with an actual class defined in your jar.

You can then make your file paths be relative to jarPath, and your program will work regardless of its working directory.

Upvotes: 1

Related Questions