16 November 2007

java.util.zip

I've just discovered that this useful API has been present in Java since version 1.1.
That's good because I don't have to add any additional library to perform the task of zipping, that would steal some additional precious embedded storage room.
XML files are notoriously redundant so the idea of gzipping an XML file before saving it onto flash can lead to significant savings.

The only problem, I had to learn a bit more about the difference in Java between byte-based and character-based streams.
As you probably already know, these two types, byte and char, are different.
Byte is an 8 bit signed type, while char is a 16 bit unsigned byte. The reason for char is to allow support for internalization and localization by carrying character set information.
Some classes use byte based streams, some others char based ones.
The java.util.zip library uses byte based streams, so in order to interface it with character based classes (like an XML parser) I needed to use some sort of bridge classes.


Examples. To Gzip a String:

String str = ...;
ByteArrayOutputStream ba = new ByteArrayOutputStream();
GZIPOutputStream gz = new GZIPOutputStream( ba );
DataOutputStream os = new DataOutputStream( gz );

os.writeBytes( str );
os.close();

byte result[] = ba.toByteArray()



To UnGzip from an InputStream:

InputStream is = ...;
GZIPInputStream igz = new GZIPInputStream( is );
InputStreamReader isr = new InputStreamReader( igz, "ISO-8859-1" );
StringBuilder strb = new StringBuilder();
int c;
while(( c = isr.read() ) != -1 )
{
strb.append( (char)c );
}
String result = strb.toString();

No comments:

Post a Comment