public static final byte[] compress(String str) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(out);
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes());
zout.closeEntry();
byte[] compressed = out.toByteArray();
zout.close();
return compressed;
}
public static final String decompress(byte[] compressed) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
ZipInputStream zin = new ZipInputStream(in);
ZipEntry entry = zin.getNextEntry();
byte[] buffer = new byte[1024];
int offset = -1;
while((offset = zin.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
String decompressed = out.toString();
out.close();
zin.close();
return decompressed;
}
public static final void main(String[] args) {
String str = "Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n"
"Compress this string/r/n";
try {
byte[] compressed = compress(str);
int compressedSize = compressed.length;
String decompressed = decompress(compressed);
int decompressedSize = decompressed.getBytes().length;
System.out.println("Compressed Size = " compressedSize);
System.out.println("Decompressed Size = " + decompressedSize);
} catch(IOException e) {
e.printStackTrace();
}
}
Simple String Compression Functions
最新推荐文章于 2025-01-13 15:16:10 发布