我有一个包含以下代码的程序:
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());
}
}
我在eclipse中将其导出为Runnable Jar。然后我将文件复制到我的Ubuntu 13.04系统上的/home/username/Desktop/
和cd
到该目录。当我运行命令java -jar Main.jar
时,我得到以下输出:
/home/username/Desktop/config
现在我运行chmod使Jar可执行,然后我去双击Jar。我从对话框中得到以下输出:
/home/username/config
为什么我会得到不同的输出?将Jar移动到其他目录会产生类似的结果。谷歌搜索和搜索SO没有解决这个问题。
答案 0 :(得分:2)
new File("config")
与运行JVM的进程的工作目录相关。当您在cd
之后从命令行运行到目录中时,那就是工作目录。
双击Ubuntu GUI中的jar不会将工作目录设置为容纳jar文件的同一目录,因此不同。
试试这个:
来自命令的 cd into /home/username
,然后输入java -jar Desktop/Main.jar
。这将打印出与双击jar时相同的内容。
如果您希望每次都获得相同的目录,请使用绝对目录名称。在Linux上,通过使用/启动目录来实现此目的。例如new File("/home/username/config")
。如果要动态查找用户主目录,请使用System.getProperty("user.home")
。
例如new File( System.getProperty("user.home") + "/config" );