2017-05-26 13 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クラス。 URLがfile:のURLであるとは決して考えるべきではありません。

代わりに、あなたは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を構築することでマニフェストを読むことができる:

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です。

もう一つの方法は、データファイルを作成するだけで、あなたはClass.getResourceまたはClass.getResourceAsStreamを使用して読み取ることができ、あなたの.jar、それを含める:

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

String revisionNumber = props.getProperty("version"); 
関連する問題