package test;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;
public class TestZip {
public static void main(String[] args) throws UnsupportedEncodingException {
String str="snowolf@zlex.org;dongliang@zlex.org;zlex.dongliang@zl";
System.out.println(str);
byte [] aa=str.getBytes("UTF-8");
System.out.println(aa.length);
byte [] bb=lengthCp(aa);
System.out.println(bb.length);
lengthDp(bb);
}
public static byte[] lengthCp(byte[] datas){
try {
ByteBuffer buffer = ByteBuffer.allocate(datas.length);
buffer.put(datas);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
dos.write(buffer.array());
dos.finish();
int len = buffer.array().length;
ByteBuffer temp = ByteBuffer
.allocate(4+baos.toByteArray().length);// 压缩前的数据长度
temp.put(intToByteArray(len));//长度校验
temp.put(baos.toByteArray());
return temp.array();
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
public static void lengthDp(byte[] data ){
byte[] datas = new byte[data.length-4];
byte[] dat = new byte[4];
try {
System.arraycopy(data,0,dat,0,4);
System.arraycopy(data,4,datas,0,data.length-4);
int a=byteArrayToInt(dat);
System.out.println(a);
ByteBuffer buffer = ByteBuffer.allocate(datas.length);
buffer.put(datas);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InflaterOutputStream dos = new InflaterOutputStream(baos);
dos.write(buffer.array());
dos.finish();
int len = buffer.array().length;
ByteBuffer temp = ByteBuffer
.allocate(baos.toByteArray().length);// 压缩前的数据长度
temp.put(baos.toByteArray());
System.out.println(new String(temp.array()));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
public static byte[] intToByteArray(int a) {
return new byte[] {
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
}