【问题标题】:Get a JAR File version number获取 JAR 文件版本号
【发布时间】:2014-08-09 23:42:11
【问题描述】:

我有一个用于集群的应用程序,以便在一个或多个失败时保持可用,并且我想实现一种方法来检查 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 文件用作其他应用程序中的库时,我得到了其他应用程序的版本号。

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

注意:我对使用静态约束的解决方案不感兴趣 'classLoader.getRessource("MyJar.jar")' 或 File("MyJar.jar")

【问题讨论】:

    标签: java jar version manifest


    【解决方案1】:

    获取实现版本的正确方法是使用Package.getImplementationVersion() method

    String version = MyClass.class.getPackage().getImplementationVersion();
    

    【讨论】:

      【解决方案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教程,谢谢。我也从这里学到了新东西。

      【讨论】:

      • 是的,我也找到了这个解决方案,但它不能解决我的问题,因为我必须知道我的 jar 文件的限定名称。我想要一个动态解决方案,它可以不受文件名等约束:/ ..
      • 好的,我有一个解决方案!谢谢你!!只是让时间发布它;)
      【解决方案3】:
      【解决方案4】:

      我终于从朋友那里得到了解决方案:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多