Deflater
Compress and uncompress a java byte array using deflater and enflater
In java a byte[] array is similar as a binary data stored in a file. So you can compress and uncompress this array content using deflater and enflater class in java. This is done completely in memory so this is very much faster than zipping or unzipping a file using java.
In this example I will show you how to compress a string by converting it to byte and then compressing storing it in compressed byte array it takes smaller memory. And when needed just extract the byte array to its full size and convert to string again.
1 CommentCompress file to gz format using java
Java programs can compress a file on a fly! All you need is just to make proper use of java.util.zip class like this
public class gZip
{
public static void compress(String src, String dest) throws java.io.IOException
{
java.util.zip.GZIPOutputStream out = new java.util.zip.GZIPOutputStream(new java.io.FileOutputStream(dest));
java.io.FileInputStream in = new java.io.FileInputStream(src);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
// Complete the GZIP file
out.finish();
out.close();
}
public static void main(String[] args)
{
try
{
compress("D://test.txt", "D://test.txt.gz");
}
catch (java.io.IOException ex)
{
ex.printStackTrace();
}
}
}
This will compress D:/test.txt to D:/test.txt.gz
No Comments