Java 访问 .jar 之外的属性文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/775389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing properties files outside the .jar?
提问by Jason S
I have a .jar file I'm putting together. I want to create a really really simple .properties file with configurable things like the user's name & other stuff, so that they can hand-edit rather than my having to include a GUI editor.
我有一个 .jar 文件要放在一起。我想创建一个非常简单的 .properties 文件,其中包含可配置的内容,例如用户名和其他内容,以便他们可以手动编辑,而不必包含 GUI 编辑器。
What I'd like to do is to be able to search, in this order:
我想要做的是能够按以下顺序进行搜索:
- a specified properties file (
args[0]
) - MyApp.properties in the current directory (the directory from which Java was called)
- MyApp.properties in the user's directory (the user.homesystem property?)
- MyApp.properties in the directory where the application .jar is stored
- 指定的属性文件 (
args[0]
) - 当前目录中的 MyApp.properties(调用 Java 的目录)
- 用户目录中的 MyApp.properties(user.home系统属性?)
- MyApp.properties 在应用程序.jar 的存放目录中
I know how to access #1 and #3 (I think), but how can I determine at runtime #2 and #4?
我知道如何访问 #1 和 #3(我认为),但是如何在运行时确定 #2 和 #4?
采纳答案by erickson
#2 is the "user.dir"system property. #3 is the "user.home" property.
#2 是“user.dir”系统属性。#3 是“user.home”属性。
#4 is a bit of a kludge no matter how you approach it. Here's an alternate technique that works if you have a class loaded from a JAR not on the system classpath.
无论你如何接近它,#4 都有些杂乱无章。如果您从不在系统类路径上的 JAR 加载了一个类,这里有一个替代技术。
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL url = new URL(src.getLocation(), "MyApp.properties");
...
}
else {
/* Fail... */
}
回答by Steve Reed
For the current working directory:
对于当前工作目录:
new File(".");
For a file named MyApp.properties in the current directory:
对于当前目录中名为 MyApp.properties 的文件:
new File(new File("."), "MyApp.properties");
回答by Chris Thornhill
For 4, you could try this. Get the classpath:
对于 4,你可以试试这个。获取类路径:
String classpath = System.getProperty("java.class.path");
Then search it for the name of your application jar:
然后搜索您的应用程序 jar 的名称:
int jarPos = classpath.indexOf("application.jar");
Parse out the path leading up to it:
解析出通向它的路径:
int jarPathPos = classpath.lastIndexOf(File.pathSeparatorChar, jarPos) + 1;
String path = classpath.substring(jarPathPos, jarPos);
Then append MyApp.properties
. Make sure to check for jarPos == -1
, meaning the jar isn't found if the classpath (perhaps when running in your dev environment).
然后附加MyApp.properties
. 确保检查jarPos == -1
,这意味着如果类路径(可能在您的开发环境中运行时),则找不到 jar。