简体   繁体   English

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

[英]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? 有没有办法用Java读取jar / war文件中的文件( maven.properties )内容? 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). JAR / WAR是一个文件,您正在寻找的是存档中的一个条目(又称为资源)。

And because it's not a file, you will need to get it as an InputStream 而且由于它不是文件,因此您需要将其作为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 如果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. If not, you will have to read the JAR / WAR like this: 如果没有,您将必须像这样阅读JAR / WAR:

     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: 现在,您可能想将InputStream加载到Properties对象中:

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

Or you can read the InputStream to a String. 或者,您可以将InputStream读取为字符串。 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. WAR和JAR文件基本上是.zip文件,因此,如果您具有包含.properties文件的文件的位置,则可以使用ZipFile将其打开并提取属性。

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: 如果是JAR文件,则可能有一种更简单的方法:您可以将其添加到类路径中,然后使用类似以下方式加载属性:

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

(assuming the properties file is in the root package) (假设属性文件在根包中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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