Read maven.properties file inside jar/war file

不打扰是莪最后的温柔 提交于 2019-12-04 19:34:55

One thing first: technically, it's not a file. The JAR / WAR is a file, what you are looking for is an entry within an archive (AKA a resource).

And because it's not a file, you will need to get it as an InputStream

  1. If the JAR / WAR is on the classpath, you can do SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"), where SomeClass is any class inside that 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. If not, you will have to read the JAR / WAR like this:

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

Now you probably want to load the InputStream into a Properties object:

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

Or you can read the InputStream to a String. This is much easier if you use a library like

Boris Pavlović
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);

This is definitely possible although without knowing your exact situation it's difficult to say specifically.

WAR and JAR files are basically .zip files, so if you have the location of the file containing the .properties file you want you can just open it up using ZipFile and extract the properties.

If it's a JAR file though, there may be an easier way: you could just add it to your classpath and load the properties using something like:

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

(assuming the properties file is in the root package)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!