Numa
Numa

Reputation: 3

Opening files located in Java jar directory, not Current Working Directory

I have a Java desktop application that I developed in NetBeans which I zip up to distribute to students. Inside this zip file I have the .jar, a "lib" directory that contains the swing-layout jar, and a directory I named "sourcefiles" that contains all the text files needed for the program.

All works fine if the jar file is double clicked, but when run from the command line (java -jar MyApp.jar), it can only find the "sourcefiles" directory if you first cd to the directory that the file is in before running the command, something that the some students forget to do. Apparently there is no way to change the current working directory from within my code. The path to "sourcefiles" is given in my code as a relative path, assuming that I am in the MyApp folder. So what can I do so that the program can be run from the command line without having to cd to the containing directory? Is there something to add this to the manifest file?

This problem is faced mostly by students using Linux, but it is the same on Mac. I assume it's the same on Windows, but I guess none of the students with Windows run it from the command line.

Upvotes: 0

Views: 1564

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533820

You can't change the default directory, but you can get the directory the Jar the class is running in and use that in your code as the base path.

String jarLocation = ThisClass.class.getProtectionDomain()
                         .getCodeSource().getLocation().getPath();

From this you can get the directory the jar is in. Most likely you will want to wrap this up as a method your students can call.

Upvotes: 1

Related Questions