开发者

How do I read in an existing jar's manifest, and append to its classpath using Ant

开发者 https://www.devze.com 2023-04-13 03:13 出处:网络
I want to add a target to my Ant script that reads in a jar\'s manifest and appends a new jar at the end. I\'ve looked at loadproperties task, and it seemed close, but unable to handle when the classp

I want to add a target to my Ant script that reads in a jar's manifest and appends a new jar at the end. I've looked at loadproperties task, and it seemed close, but unable to handle when the classpath is split up among multiple lines. So does anyone know if this is possible with the out-开发者_开发知识库of-the-box Ant tasks?


The manifest task in update mode would seem the obvious answer.


Based on the code here, I modified it to read in the existing classpath, append a new jar file at the end and then save it to a property. At that point, it's easy to write back out using the manifest task.

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;
        }

    }
}

The getters/setters/utility methods omitted for space. Then the Ant code looks like this:

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号