我正在创建一个可执行 JAR,它将在运行时从文件中读取一组属性。目录结构类似于:
/some/dirs/executable.jar
/some/dirs/executable.properties
有没有一种方法可以在 executable.jar 文件中设置属性加载器类以从 jar 所在的目录加载属性,而不是对目录进行硬编码。
我不想将属性放在 jar 本身中,因为属性文件需要是可配置的。
最佳答案
为什么不直接将属性文件作为参数传递给您的主要方法?这样您就可以按如下方式加载属性:
public static void main(String[] args) throws IOException {
Properties props = new Properties();
props.load(new BufferedReader(new FileReader(args[0])));
System.setProperties(props);
}
备选方案:如果您想获取 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");
}
... 其中 MyClass
是您的 jar 文件中的一个类。这不是我推荐的东西——如果你的应用程序在不同 jar 文件的类路径上有多个 MyClass
实例怎么办(每个 jar 在不同的目录中)?也就是说,您永远无法真正保证 MyClass
是从您认为的 jar 中加载的。
关于java - 从 JAR 目录读取属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1301373/