1

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

问候, 约翰-基斯

4

3 回答 3

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);
于 2011-03-11T08:39:00.140 回答
4

首先是一件事:从技术上讲,它不是一个文件。JAR / WAR 是一个文件,您正在寻找的是档案中的一个条目(又名资源)。

而且因为它不是一个文件,所以你需要将它作为一个InputStream

  1. 如果 JAR / WAR 在类路径上,您可以这样做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"));
    

现在您可能想要将 加载InputStreamProperties对象中:

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

或者你可以读到InputStream一个字符串。如果您使用类似的库,这会容易得多

于 2011-03-11T08:42:53.307 回答
1

这绝对是可能的,尽管在不知道您的确切情况的情况下很难具体说明。

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

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

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

(假设属性文件在根包中)

于 2011-03-11T08:39:07.660 回答