Leh*_*ane 5 java jar properties path
我正在创建一个可执行的JAR,它将在运行时从一个文件中读取一组属性.目录结构将类似于:
/some/dirs/executable.jar
/some/dirs/executable.properties
Run Code Online (Sandbox Code Playgroud)
有没有办法在executable.jar文件中设置属性加载器类来从jar所在的目录加载属性,而不是硬编码目录.
我不想将属性放在jar本身,因为属性文件需要是可配置的.
Ada*_*ski 13
为什么不直接将属性文件作为参数传递给main方法?这样您可以按如下方式加载属性:
public static void main(String[] args) throws IOException {
Properties props = new Properties();
props.load(new BufferedReader(new FileReader(args[0])));
System.setProperties(props);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法:如果你想得到jar文件的当前目录,你需要做一些令人讨厌的事情:
CodeSource codeSource = MyClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
if (jarDir != null && jarDir.isDirectory()) {
File propFile = new File(jarDir, "myFile.properties");
}
Run Code Online (Sandbox Code Playgroud)
... MyClass你的jar文件中有一个类.这不是我推荐的东西 - 如果你的应用程序MyClass在不同jar文件(不同目录中的每个jar)的类路径上有多个实例,该怎么办?即你永远不能保证MyClass从你认为的罐子里装满了.
| 归档时间: |
|
| 查看次数: |
9860 次 |
| 最近记录: |