【问题标题】:Reading properties file from JAR directory从 JAR 目录读取属性文件
【发布时间】:2009-08-19 17:16:22
【问题描述】:
我正在创建一个可执行的 JAR,它将在运行时从文件中读取一组属性。目录结构类似于:
/some/dirs/executable.jar
/some/dirs/executable.properties
有没有办法在executable.jar文件中设置属性加载器类来从jar所在的目录加载属性,而不是对目录进行硬编码。
我不想将属性放入 jar 本身,因为属性文件需要可配置。
【问题讨论】:
标签:
java
properties
path
jar
【解决方案1】:
为什么不直接将属性文件作为参数传递给您的 main 方法?这样您就可以按如下方式加载属性:
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 文件(每个 jar 在不同的目录中)的类路径上有多个 MyClass 实例怎么办?也就是说,您永远无法真正保证 MyClass 是从您认为的 jar 中加载的。
【解决方案2】:
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}