我正在创建一个可执行JAR,它将在运行时从文件中读取一组属性。该目录结构是这样的:从JAR目录中读取属性文件
/some/dirs/executable.jar
/some/dirs/executable.properties
有没有在executable.jar文件设置该属性加载类的方式来加载从罐子中,而不是硬编码的目录属性目录。
我不想将属性放入jar本身,因为属性文件需要配置。
我正在创建一个可执行JAR,它将在运行时从文件中读取一组属性。该目录结构是这样的:从JAR目录中读取属性文件
/some/dirs/executable.jar
/some/dirs/executable.properties
有没有在executable.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中加载的。
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");
}
}
http://stackoverflow.com/questions/775389/accessing-properties-files-outside-the-jar的可能重复 – 2010-04-01 20:39:38