java zlib压缩
时间: 2023-10-16 12:07:10 浏览: 77
Java中可以使用java.util.zip包中的Deflater和Inflater类来进行zlib压缩和解压缩。
以下是一个简单的示例代码:
```
import java.util.zip.*;
public class ZlibCompression {
public static void main(String[] args) {
String input = "Hello, world!";
byte[] uncompressed = input.getBytes();
// 压缩
Deflater deflater = new Deflater();
deflater.setInput(uncompressed);
deflater.finish();
byte[] compressed = new byte[uncompressed.length];
int compressedLength = deflater.deflate(compressed);
deflater.end();
// 解压缩
Inflater inflater = new Inflater();
inflater.setInput(compressed, 0, compressedLength);
byte[] decompressed = new byte[uncompressed.length];
int decompressedLength = inflater.inflate(decompressed);
inflater.end();
String output = new String(decompressed, 0, decompressedLength);
System.out.println(output); // 输出 "Hello, world!"
}
}
```
阅读全文