从JAR目录中读取属性文件 [英] Reading properties file from JAR directory

查看:157
本文介绍了从JAR目录中读取属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可执行的JAR,它将在运行时从一个文件中读取一组属性。目录结构类似于:

I’m creating an executable JAR that will read in a set of properties at runtime from a file. The directory structure will be something like:

/some/dirs/executable.jar
/some/dirs/executable.properties

有没有办法在executable.jar文件中设置属性加载器类来加载jar所在目录中的属性,而不是对目录进行硬编码。

Is there a way of setting the property loader class in the executable.jar file to load the properties from the directory that the jar is in, rather than hard-coding the directory.

我不想把属性放在jar本身,因为属性文件需要配置。

I don't want to put the properties in the jar itself as the properties file needs to be configurable.

推荐答案

为什么不将属性文件作为参数传递给main方法?这样你可以按如下方式加载属性:

Why not just pass the properties file as an argument to your main method? That way you can load the properties as follows:

public static void main(String[] args) throws IOException {
  Properties props = new Properties();
  props.load(new BufferedReader(new FileReader(args[0])));
  System.setProperties(props);
}

另一种选择:如果你想得到jar文件的当前目录你我需要做一些讨厌的事情:

The alternative: If you want to get the current directory of your jar file you need to do something nasty like:

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文件(不同目录中的每个jar)的类路径上有多个 MyClass 实例怎么办?即你永远不能保证从你认为的罐子里加载 MyClass

... where MyClass is a class from within your jar file. It's not something I'd recommend though - What if your app has multiple MyClass instances on the classpath in different jar files (each jar in a different directory)? i.e. You can never really guarantee that MyClass was loaded from the jar you think it was.

这篇关于从JAR目录中读取属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆