středa 16. září 2009

Linux: How to Convert Binary File into Byte Array

Sometimes, a programmer needs to embed a content of a binary file into a program, usually as an array of bytes. For instance, I needed to embed an icon into a Java code, to be really sure the icon is always available for the program. So I have saved an icon in a GIF format and then used the od command. But the result was an unusable list of octal numbers. After a minute with playing, I have found a feasible solution
od -A n -v -t d1 image.gif | sed -e 's/^ *//g' -e 's/  */,/g' -e 's/$/,/g'
I have copied a result into my Java code as
private static final byte[] MISSING_ICON_BYTES = new byte[] { /* copy result here */ };
public static final ImageIcon MISSING_ICON = new ImageIcon(MISSING_ICON_BYTES);

ú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/"/>
    <exclude name="META-INF/"/>
  <zipfileset file="" fullpath=""/>
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.