盒子
盒子

java-zip-compress

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import com.sun.xml.internal.messaging.saaj.util.Base64;


public class TestDemo {

public static void main(String[] args) throws IOException {
String text = "I was not delivered unto this world in defeat, nor does failure course in my veins. I am not a sheep waiting to be prodded by my shepherd. I am a lion and I refuse to talk, to walk, to sleep with the sheep. I will hear not those who weep and complain, for their disease is contagious. Let them join the sheep";
String a = zip(text);
System.out.println(a);
}

public static final String zip(String str) {
if (str == null)
return null;
byte[] compressed;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null;
String compressedStr = null;
try {
out = new ByteArrayOutputStream();

zout = new ZipOutputStream(out);

zout.putNextEntry(new ZipEntry(""));
zout.write(str.getBytes());

zout.close();

compressed = out.toByteArray();

compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);

} catch (IOException e) {
compressed = null;
} finally {
if (zout != null) {
try {
zout.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return compressedStr;
}
}