Java实现对string字符串的deflate算法的压缩和解压
时间: 2023-12-02 12:04:23 浏览: 134
缩,有什么推荐的库或者工具吗?
对于Java实现string字符串的deflate算法的压缩和解压缩,您可以考虑使用Java自带的压缩库java.util.zip中的Deflater和Inflater类。下面是一个简单的样例代码,可以实现对字符串进行deflate压缩和解压缩:
```java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class StringDeflater {
public static byte[] compress(String str) throws IOException {
byte[] input = str.getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
byte[] buffer = new byte[1024];
while (!compresser.finished()) {
int count = compresser.deflate(buffer);
baos.write(buffer, 0, count);
}
compresser.end();
return baos.toByteArray();
}
public static String decompress(byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompresser = new Inflater();
decompresser.setInput(input);
byte[] buffer = new byte[1024];
while (!decompresser.finished()) {
int count = decompresser.inflate(buffer);
baos.write(buffer, 0, count);
}
decompresser.end();
return baos.toString();
}
public static void main(String[] args) throws IOException {
String str = "Hello, world!";
System.out.println("Original string: " + str);
byte[] compressed = compress(str);
System.out.println("Compressed string: " + new String(compressed, "UTF-8"));
String decompressed = decompress(compressed);
System.out.println("Decompressed string: " + decompressed);
}
}
```
在这个样例代码中,compress和decompress分别实现了数据的压缩和解压缩,使用Deflater和Inflater类来完成deflate操作。您可以通过调用compress方法将字符串压缩,并将返回值存储到byte数组中,也可以使用decompress方法解压缩byte数组,并将解压缩后的字符串返回。
阅读全文