在jar / war文件中读取maven.properties文件

时间:2011-03-11 08:30:50

标签: java maven readfile

有没有办法用Java读取jar / war文件中的文件内容(maven.properties)?我需要从磁盘读取文件,当它没有被使用时(在内存中)。有关如何做到这一点的任何建议吗?

此致 约翰-基斯

3 个答案:

答案 0 :(得分:8)

String path = "META-INF/maven/pom.properties";

Properties prop = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream(path );
try {
  prop.load(in);
} 
catch (Exception e) {

} finally {
    try { in.close(); } 
    catch (Exception ex){}
}
System.out.println("maven properties " + prop);

答案 1 :(得分:5)

首先要做的一件事:从技术上讲,它不是文件。 JAR / WAR是一个文件,您要查找的是存档中的条目(AKA是一个资源)。

由于它不是文件,因此您需要将其作为InputStream

  1. 如果JAR / WAR在 classpath,你可以做SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"),其中SomeClass是JAR / WAR中的任何类

    // these are equivalent:
    SomeClass.class.getResourceAsStream("/abc/def");
    SomeClass.class.getClassLoader().getResourceAsStream("abc/def");
    // note the missing slash in the second version
    
  2. 如果没有,你必须像这样阅读JAR / WAR:

    JarFile jarFile = new JarFile(file);
    InputStream inputStream =
        jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
    

  3. 现在您可能希望将InputStream加载到Properties对象中:

    Properties props = new Properties();
    // or: Properties props = System.getProperties();
    props.load(inputStream);
    

    或者您可以将InputStream读取为字符串。如果您使用像

    这样的库,这会容易得多

答案 2 :(得分:1)

这绝对是可能的,虽然不知道你的确切情况但很难具体说明。

WAR和JAR文件基本上都是.zip文件,所以如果您拥有包含.properties文件的文件的位置,您可以使用ZipFile打开它并提取属性。

如果它是一个JAR文件,可能有一种更简单的方法:你可以将它添加到类路径并使用类似的东西加载属性:

SomeClass.class.getClassLoader().getResourceAsStream("maven.properties"); 

(假设属性文件位于根包中)

相关问题