package af.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; /** * Created by IntelliJ IDEA. * User: Administrator * Date: 25/8/2555 * To change this template use File | Settings | File Templates. */ public class Zip { public static byte[] compressBytes(byte[] input) throws UnsupportedEncodingException, IOException { Deflater df = new Deflater(); //this function mainly generate the byte code //df.setLevel(Deflater.BEST_COMPRESSION); df.setInput(input); ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length); //we write the generated byte code in this array df.finish(); byte[] buff = new byte[1024]; //segment segment pop....segment set 1024 while (!df.finished()) { int count = df.deflate(buff); //returns the generated code... index baos.write(buff, 0, count); //write 4m 0 to count } baos.close(); byte[] output = baos.toByteArray(); //System.out.println("Original: " + input.length); //System.out.println("Compressed: " + output.length); return output; } public static byte[] extractBytes(byte[] input) throws UnsupportedEncodingException, IOException, DataFormatException { Inflater ifl = new Inflater(); //mainly generate the extraction //df.setLevel(Deflater.BEST_COMPRESSION); // Log.i(input +""); ifl.setInput(input); ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length); byte[] buff = new byte[1024]; while (!ifl.finished()) { int count = ifl.inflate(buff); baos.write(buff, 0, count); } baos.close(); byte[] output = baos.toByteArray(); //System.out.println("Original: " + input.length); //System.out.println("Extracted: " + output.length); //System.out.println("Data:"); //System.out.println(new String(output)); return output; } public static void compressFile(String src, String dest) throws 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(); } }