问题
As the title says. How do you decompress a compressed string which was compressed with zlib deflate? What is the solid way of doing it with an explanation?
回答1:
Try this - it is a minimal working example:
package zlib.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/**
* Created by keocra on 08.10.15.
*/
public class Main {
private final static String inputStr = "Hello World!";
public static void main(String[] args) throws Exception {
System.out.println("Will zlib compress following string: " + inputStr);
// will compress "Hello World!"
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
dos.write(inputStr.getBytes());
dos.flush();
dos.close();
// at this moment baos.toByteArray() holds the compressed data of "Hello World!"
// will decompress compressed "Hello World!"
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
InflaterInputStream iis = new InflaterInputStream(bais);
String result = "";
byte[] buf = new byte[5];
int rlen = -1;
while ((rlen = iis.read(buf)) != -1) {
result += new String(Arrays.copyOf(buf, rlen));
}
// now result will contain "Hello World!"
System.out.println("Decompress result: " + result);
}
}
You should also easily be able to extend this example to compress/decompress files.
Hope it helps ;-)
Further readings:
- http://docs.oracle.com/javase/7/docs/api/java/util/zip/DeflaterOutputStream.html
- https://docs.oracle.com/javase/7/docs/api/java/util/zip/InflaterInputStream.html
回答2:
I found this article in Google, it explains how to compress and decompress in java using zlib, hope it helps
来源:https://stackoverflow.com/questions/33020765/java-decompress-a-string-compressed-with-zlib-deflate