2014-06-19 115 views
4

我有一个应用程序用于群集,以保持它可用,如果一个或多个失败,我想实现一种方法来检查在Java中的jar文件的版本。获取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文件作为LIBRAIRIE在另一个应用程序中,我得到另一个应用程序的版本号。

所以我的问题是,我如何获得包含MyClass的jar的清单?

注:我没有兴趣在溶液中使用静态约束像 'classLoader.getRessource( “MyJar.jar”)' 或文件( “MyJar.jar”)

回答

0

最后我从朋友那里获得了解决方案:

// 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) 
2

您可以编写这样的:

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" 

请参阅this教程,谢谢。我也从这里学到新东西。

+0

是的,我也发现这个解决方案,但它不能解决我的问题,因为我必须知道我的jar文件的限定名称。我想要一个动态的解决方案,可以在不受限制的情况下工作,如文件名:/ .. – Kraiss

+0

好的,让我在某个时间后再次发布。 –

+0

好吧,我有一个解决方案!谢谢你!!只是让时间来发布它;) – Kraiss