java gzip 压缩字符串
时间: 2023-08-10 10:04:42 浏览: 155
您可以使用 Java 中的 GZIPOutputStream 类来压缩字符串,示例代码如下:
```java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipExample {
public static void main(String[] args) throws IOException {
String str = "Hello, world!"; // 待压缩字符串
// 压缩字符串
byte[] compressed = compress(str);
System.out.println("Compressed: " + new String(compressed, StandardCharsets.UTF_8));
// 解压字符串
String decompressed = decompress(compressed);
System.out.println("Decompressed: " + decompressed);
}
public static byte[] compress(String str) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return out.toByteArray();
}
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
try (GZIPInputStream gzip = new GZIPInputStream(in)) {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((len = gzip.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
return out.toString(StandardCharsets.UTF_8.name());
}
}
}
```
在上述示例代码中,compress() 方法输入一个字符串,输出一个经过 GZIP 压缩后的字节数组;decompress() 方法输入一个经过 GZIP 压缩的字节数组,输出一个解压后的字符串。
阅读全文