[英]Get a JAR File version number
我有一個用於群集的應用程序,以便在一個或多個失敗時保持可用,並且我想實現一種方法來檢查java中jar文件的版本。
我有這段代碼來做(例如:在MyClass類中):
URLClassLoader cl = (URLClassLoader) (new MyClass ())
.getClass().getClassLoader();
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
attributes = manifest.getMainAttributes();
String version = attributes.getValue("Implementation-Version");
當我將jar作為應用程序運行時它工作正常但是當我在其他應用程序中使用jar文件作為librairie時,我得到了另一個應用程序的版本號。
所以我的問題是,我怎樣才能獲得包含MyClass的jar的清單?
注意:我對使用靜態約束的解決方案不感興趣,比如'classLoader.getRessource(“MyJar.jar”)'或File(“MyJar.jar”)
獲取實現版本的正確方法是使用Package.getImplementationVersion()方法 :
String version = MyClass.class.getPackage().getImplementationVersion();
您可以像:
java.io.File file = new java.io.File("/packages/file.jar"); //give path and file name
java.util.jar.JarFile jar = new java.util.jar.JarFile(file);
java.util.jar.Manifest manifest = jar.getManifest();
String versionNumber = "";
java.util.jar.Attributes attributes = manifest.getMainAttributes();
if (attributes!=null){
java.util.Iterator it = attributes.keySet().iterator();
while (it.hasNext()){
java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next();
String keyword = key.toString();
if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")){
versionNumber = (String) attributes.get(key);
break;
}
}
}
jar.close();
System.out.println("Version: " + versionNumber); //"here it will print the version"
看到這個教程,謝謝。 我也從這里學到新東西。
如果您知道jar中的類,則可以從ProtectionDomain的CodeSource獲取jar的位置。
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getProtectionDomain%28%29
http://docs.oracle.com/javase/7/docs/api/java/security/ProtectionDomain.html#getCodeSource%28%29
http://docs.oracle.com/javase/7/docs/api/java/security/CodeSource.html#getLocation%28%29
最后我從朋友那里得到了解決方案:
// Get jarfile url
String jarUrl = JarVersion.class
.getProtectionDomain().getCodeSource()
.getLocation().getFile();
JarFile jar = new JarFile(new File(jarUrl));
Manifest manifest = jar.getManifest();
Attributes attributes = manifest.getMainAttributes();
String version = attributes.getValue(IMPLEMENTATION_VERSION)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.