简体   繁体   中英

Read maven.properties file inside jar/war file

Is there a way to read the content of a file ( maven.properties ) inside a jar/war file with Java? I need to read the file from disk, when it's not used (in memory). Any advise on how to do this?

Regards, Johan-Kees

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);

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM