Zip.java
2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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();
}
}