D
dave
I try to compress a string, like this :
private byte[] compressMsg(String msg)
{
try
{
byte[] input = msg.getBytes("UTF-8");
byte[] output = new byte[input.length];
Deflater compresser = new Deflater();
compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
compresser.setInput(input);
compresser.finish();
compresser.deflate(output);
return output;
}
catch (java.io.UnsupportedEncodingException uee)
{
uee.printStackTrace();
return null;
}
}
It seems to work, it returns a byte-array with some unreadable
(deflated) data which transfers nicely back into the original string
when inflated.
But, the returned byte-array is exactly the same size as the input-array,
so I gain no advantage from this compression (...).
This is, of course because you have to declare the output-array before
starting the deflation and since you don't know how much the data will
shrink, you can only make it as big as the input.
(I also notice that the deflated file contains mostly zero's, but this seems
not to be 'empty' data, because if I remove these, the file will not be
inflated back correctly).
So my question is :
How should this code be modified to return a byte-array with
compressed data that is actually smaller than the original ?
private byte[] compressMsg(String msg)
{
try
{
byte[] input = msg.getBytes("UTF-8");
byte[] output = new byte[input.length];
Deflater compresser = new Deflater();
compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
compresser.setInput(input);
compresser.finish();
compresser.deflate(output);
return output;
}
catch (java.io.UnsupportedEncodingException uee)
{
uee.printStackTrace();
return null;
}
}
It seems to work, it returns a byte-array with some unreadable
(deflated) data which transfers nicely back into the original string
when inflated.
But, the returned byte-array is exactly the same size as the input-array,
so I gain no advantage from this compression (...).
This is, of course because you have to declare the output-array before
starting the deflation and since you don't know how much the data will
shrink, you can only make it as big as the input.
(I also notice that the deflated file contains mostly zero's, but this seems
not to be 'empty' data, because if I remove these, the file will not be
inflated back correctly).
So my question is :
How should this code be modified to return a byte-array with
compressed data that is actually smaller than the original ?