簡體   English   中英

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

[英]Read maven.properties file inside jar/war file

有沒有辦法用Java讀取jar / war文件中的文件( maven.properties )內容? 當不使用文件(在內存中)時,我需要從磁盤讀取文件。 任何建議如何做到這一點?

問候,約翰·基斯

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

首先要注意的是:從技術上講,它不是文件。 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")); 

現在,您可能想將InputStream加載到Properties對象中:

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

或者,您可以將InputStream讀取為字符串。 如果您使用類似

這絕對是可能的,盡管在不知道您的確切情況的情況下很難說清楚。

WAR和JAR文件基本上是.zip文件,因此,如果您具有包含.properties文件的文件的位置,則可以使用ZipFile將其打開並提取屬性。

如果是JAR文件,則可能有一種更簡單的方法:您可以將其添加到類路徑中,然后使用類似以下方式加載屬性:

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

(假設屬性文件在根包中)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM