如何读取现有jar的清单,并使用Ant附加到其类路径

时间:2011-10-14 06:13:08

标签: java ant

我想在我的Ant脚本中添加一个目标,该脚本读取jar的清单并在最后添加一个新的jar。我查看了loadproperties任务,它似乎很接近,但是当类路径被分成多行时无法处理。那么有人知道这是否可以通过开箱即用的Ant任务实现?

2 个答案:

答案 0 :(得分:1)

update模式中的manifest task似乎是明显的答案。

答案 1 :(得分:0)

基于代码here,我将其修改为在现有类路径中读取,在末尾追加一个新的jar文件,然后将其保存到属性中。此时,使用清单任务回写很容易。

public void execute() throws BuildException {
    validateAttributes();

    checkFileExists();

    JarFile jarFile = null;     
    Manifest manifest = null;

    try {
        jarFile = new JarFile(directory + "/" + jar);
        manifest = jarFile.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String currClasspath = attributes.getValue("Class-Path");

        String newClasspath = currClasspath.concat(" ").concat(append);

        getProject().setProperty(propertyName, newClasspath);           
    } catch (IOException e) {
        throw new BuildException();
    } finally {
        if (manifest != null) {
            manifest = null;
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {}
            jarFile = null;
        }

    }
}

空格中省略了getters / setters / utility方法。然后Ant代码如下所示:

<target name="addToClasspath" depends="build">
    <property name="testPath" value="C:/"/>     

    <taskdef name="manifestAppender" classname="ClasspathAppender" />

    <manifestAppender dir="${testPath}" jar="wbclasspath.jar" append="test.jar" property="newClasspath" />

    <echo>Manifest class-path: ${newClasspath}</echo>

    <jar destfile="${testPath}/wbclasspath.jar">
        <manifest>
            <attribute name="Class-Path" value="${newClasspath}" />
        </manifest>
    </jar>      
</target>