úterý 15. září 2009

Ant: Removing a File from ZIP or JAR

I was facing a common problem with building a Java project by Ant: how to remove one file, and how to replace another file in a JAR (or ZIP) file. Many folks on the web, e.g. here and here, advice to unzip the JAR, delete and replace what's needed, and then create JAR again. But I have found out a simpler solution using a <zipfileset> resource pattern:
<delete file="new.jar">
<zip file="new.jar">
  <zipfileset src="old.jar">
    <exclude name="META-INF/replace.properties"/>
    <exclude name="META-INF/remove.properties"/>
  <zipfileset file="file-to-replace.properties" fullpath="source-file-to-be-replaced.properties"/>
You can use any of Ant resources. I personally like zipfileset, because it allows to specify the fullpath attribute, which is the simple way how to change a name of a source file. The <exclude> element is like "delete file" command in this example.

The Ant jar task can be used instead of the zip task, too. But then it has to be specified the META-INF/MANIFEST.MF also, otherwise the jar task creates a new one.

The zip task has one unpleasant "feature". It does not create the file new.jar, if it is newer (has greater timestamp) than the file old.jar. So, I recommend to delete the new.jar file first.

Žádné komentáře: