Reputation: 12249
I have a program with the following code:
import java.io.File;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
File file = new File("config");
JOptionPane.showMessageDialog(null, file.getAbsolutePath());
System.out.println(file.getAbsolutePath());
}
}
I export this as a Runnable Jar in eclipse. Then I copy the file to /home/username/Desktop/
on my Ubuntu 13.04 system and cd
to that directory. When I run the command java -jar Main.jar
, I get the following output:
/home/username/Desktop/config
Now I run chmod to make the Jar executable, and then I go and double click on the Jar. I get the following output from the dialog:
/home/username/config
Why am I getting different output? Moving the Jar to other directories result in similar results. Googling and searching SO shed no light on this issue.
Upvotes: 0
Views: 118
Reputation: 11927
new File("config")
is relative to the working directory of the process running the JVM. When you run from the command line after cd
'ing into the directory then that is the working directory.
Double clicking the jar from the Ubuntu GUI is not setting the working directory to the same directory that houses the jar file, thus the difference.
Try this:
cd into /home/username
from the command like, then type java -jar Desktop/Main.jar
. That will print out the same as when you double clicked on the jar.
If you would like to get the same directory each time, then use an absolute directory name. On Linux one does this by starting the directory with a /. eg new File("/home/username/config")
. If you want to find the users home directory dynamically then use System.getProperty("user.home")
.
eg new File( System.getProperty("user.home") + "/config" );
Upvotes: 2