给Jar包添加版本信息

本文详细介绍如何在Java中为JAR包添加版本信息,包括Manifest文件的创建与修改,以及如何在代码中读取这些版本信息。通过具体示例,展示了如何编译和执行带有版本信息的JAR包,并提供了获取JAR包Specification-Version和Implementation-Version的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://blog.youkuaiyun.com/u013063153/article/details/53580424

我们有下面的包代码:
 

package cn.outofmemory;
 
public class Hello {
 public static void main(String[] args) {
    new Hello().say("Hello World!");
    }
 
 public void say(String s) {
    System.out.println(s);
 }
}

要给jar包添加版本信息,需要先创建 MANIFEST.MF 文件 :
 

Manifest-Version: 1.0
Main-Class: cn.outofmemory.Hello

编译执行jar包:

>jar cvfm hello.jar MANIFEST.MF cn\outofmemory\Hello.class
 
>java -jar hello.jar
Hello World!

修改manifest 文件来包含版本信息:

Manifest-Version: 1.0
Main-Class: com.rgagnon.Hello
Specification-Version: 2.1
Implementation-Version: 1.1

修改Hello类来显示版本信息

package cn.outofmemory;
 
public class Hello {
 public static void main(String[] args) {
    new Hello().say("Hello World!");
    }
 
 Hello() {
   Package p = this.getClass().getPackage();
   System.out.println("Hello Specification Version : " 
                         + p.getSpecificationVersion());
   System.out.println("Hello Implementation Version : " 
                         + p.getImplementationVersion());
 }
 
 public void say(String s) {
    System.out.println(s);
 }
}

编译并执行Hello

> jar cvfm hello.jar MANIFEST.MF cn\outofmemory\Hello.class
 
> java -jar hello.jar
Specification Version : 2.1
Implementation Version : 1.1
Hello World!

下面的例子,打开一个jar包并修改其版本信息:

package cn.outofmemory.howto;
 
import java.util.jar.*;
 
public class JarUtils {
  public static String getJarImplementationVersion(String jar)
       throws java.io.IOException
  {
    JarFile jarfile = new JarFile(jar);
    Manifest manifest = jarfile.getManifest();
    Attributes att = manifest.getMainAttributes();
    return att.getValue("Implementation-Version");
  }
 
  public static String getJarSpecificationVersion(String jar)
       throws java.io.IOException
  {
    JarFile jarfile = new JarFile(jar);
    Manifest manifest = jarfile.getManifest();
    Attributes att = manifest.getMainAttributes();
    return att.getValue("Specification-Version");
  }
  public static void main(String[] args) throws java.io.IOException{
    String javaMailJar = "C:/Program Files/Java/jre1.5.0/lib/mail.jar";
 
    System.out.println("Specification-Version: " 
        + JarUtils.getJarSpecificationVersion(javaMailJar));
    System.out.println("Implementation-Version: " 
        + JarUtils.getJarImplementationVersion(javaMailJar));
    /*
     * output :
     *      Specification-Version: 1.3
     *      Implementation-Version: 1.3.1
     */
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值