【发布时间】:2011-09-09 22:17:42
【问题描述】:
我不确定我是否对我的 c++ 背景感到困惑,但是...
我正在编写(学习)一个 Java 应用程序,它将加载到带有配置日期的文本文件中。有点像 INI 文件。
我认为我可以处理的文件的实际读取和处理。难倒我的是文件位置。
我想将这个额外的文本文件存储在与 jar 应用程序文件相同的目录中。但是,我不确定该应用程序文件在客户端计算机上的什么位置——例如在哪个目录中。而且,由于我需要完整路径来确保加载文件,因此我需要一种在运行时以编程方式查找 jar 文件路径的方法。
环顾四周,我以为我找到了一些东西,但在测试中它给了我调用它的类文件的位置:
String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (applicationDir.endsWith(".exe"))
{
applicationDir = new File(applicationDir).getParent();
}
else
{
// Add the path to the class files
applicationDir += getClass().getName().replace('.', '/');
// Step one level up as we are only interested in the
// directory containing the class files
applicationDir = new File(applicationDir).getParent();
}
那么,我还能做些什么来找到 jar 文件的实际路径? (也不是当前的工作目录,因为它可以改变,所以 System.getProperty("user.dir") 也不适合我)
【问题讨论】:
-
也许this previous answer 会有所帮助。