2011-03-11 38 views
1

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

問候, 約翰 - 基斯

回答

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

現在,你可能希望通過InputStream加載到Properties對象:

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

或者你可以閱讀InputStream爲字符串。這是容易得多,如果你使用一個庫像

  • Apache Commons/IO

    String str = IOUtils.toString(inputStream) 
    
  • Google Guava

    String str = CharStreams.toString(new InputStreamReader(inputStream)); 
    
7
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); 
+2

+1'ClassLoader.getSystemResourceAsStream()'不知道那個 – 2011-03-11 08:44:22

1

這絕對是可能的,雖然不知道您的具體情況很難具體說了。

WAR和JAR文件基本上是.zip文件,所以如果你有包含的.properties文件你願意,你可以打開它,使用ZipFile並提取屬性的文件的位置。

如果它是一個JAR文件雖然,有可能是一個更簡單的方法:你可以只把它添加到你的classpath並使用類似的加載性能:

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

(假設屬性文件是根包)