在 Java 中定位外部文件
我不确定我是否对我的 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") 对我也不起作用)
I'm not sure if I'm confused from my c++ background but...
I'm writing(learning) a Java application that will load in a text file with configuration date. Kindof like an INI file.
The actual reading & processing of the file I think I can handle. It's the file location that is stumping me.
I want to have this extra text file stored in the same directory as the jar application file. However, I won't know for sure where this application file is on the client computer - as in what directory. And, as I need the full path to ensure loading of the file, I need a way to programatically find the path to the jar file at run-time.
Looking around I thought I found something, but in testing it was giving me the location to the class file that was calling it:
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();
}
So, what else can I do to find the actual path to the jar file? (And not the current working directory either, as that can change, so System.getProperty("user.dir") doesn't work for me either)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将您的ini(在java中我们使用资源包 - .properties - 实际上)放在类路径中并通过 类加载器。
编辑:如果您决定使用资源包,则可以直接跳过使用类加载器,请参阅 这个
You can put your ini (in java we use resource bundles - .properties - actually) in classpath and load it via ClassLoader.
edit: If you decide to use resource bundles, you can skip using classloader directly, see this