2017-05-26 54 views
-1

通過了解jar的名稱和位置,是否有抓取它的清單並獲取其屬性的方法?通過知道它的位置獲取Jar文件的清單

我有以下代碼:

public static String readRevision() throws IOException { 

    URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation(); 
    String jarLocation = new File(jarLocationUrl.toString()).getParent(); 
    String jarFilename = new File(jarLocationUrl.toString()).getAbsoluteFile().getName(); 

    // This below is what I want to get from the manifest 
    String revision = manifest.getAttributes("Revision-Number").toString(); 

    return revision; 
+1

https://docs.oracle.com/javase/8 /docs/api/java/util/jar/JarFile.html#JarFile-java.io.File-,https://docs.oracle.com/javase/8/docs/api/java/util/jar/JarFile。 HTML#getManifest-- –

回答

1

大多數標準屬性可以直接從Package類閱讀:

String version = MyApplication.class.getPackage().getSpecificationVersion(); 

要閱讀定製atttributes,不使用java。 io.File類。您絕對不應該假設某個網址是file:網址。

相反,你可以使用一個JarInputStream

Manifest manifest; 
try (JarInputStream jar = new JarInputStream(ljarLocationUrl.openStream())) { 
    manifest = jar.getManifest(); 
} 

Attribute.Name name = new Attribute.Name("Revision-Number"); 
String revisionNumber = (String) manifest.getMainAttributes().get(name); 

或者,你可以直接通過構建JarURLConnection複合網址閱讀清單:

URL manifestURL = new URL("jar:" + jarLocationUrl + "!/META-INF/MANIFEST.MF"); 

Manifest manifest; 
try (InputStream manifestSource = manifestURL.openStream()) { 
    manifest = new Manifest(manifestSource); 
} 

Attribute.Name name = new Attribute.Name("Revision-Number"); 
String revisionNumber = (String) manifest.getMainAttributes().get(name); 

注意ProtectionDomain.getCodeSource() can return null。在應用程序中指定版本號的更好方法是將其放入清單的Specification-Version或Implementation-Version屬性中,以便從Package方法中讀取它。請記住,雖然Implementation-Version是一個自由格式的字符串,a Specification-Version value must consist of groups of ASCII digits separated by periods

另一種方法是簡單地創建一個數據文件,並將其包含在你的.jar,然後你就可以讀取使用Class.getResourceClass.getResourceAsStream

Properties props = new Properties(); 
try (InputStream stream = MyApplication.class.getResourceAsStream("application.properties")) { 
    props.load(stream); 
} 

String revisionNumber = props.getProperty("version");