java gzip 压缩率
时间: 2023-11-25 21:51:20 浏览: 150
根据提供的引用内容,我们可以使用Java中的GZIP压缩方式来实现压缩和解压缩。GZIP压缩方式是一种常用的压缩方式,它可以提供比ZIP压缩方式更好的性能。下面是一个Java程序,用于演示如何使用GZIP压缩和解压缩,并计算压缩率:
```java
import java.io.*;
import java.util.zip.*;
public class GzipExample {
public static void main(String[] args) throws IOException {
String inputString = "This is a test string for GZIP compression and decompression.";
byte[] input = inputString.getBytes("UTF-8");
// 压缩
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOutput = new GZIPOutputStream(baos);
gzipOutput.write(input);
gzipOutput.close();
byte[] compressed = baos.toByteArray();
// 解压缩
ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
GZIPInputStream gzipInput = new GZIPInputStream(bais);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = gzipInput.read(buffer)) != -1) {
baos2.write(buffer, 0, len);
}
String outputString = baos2.toString("UTF-8");
// 计算压缩率
double compressionRatio = (double) compressed.length / (double) input.length;
// 输出结果
System.out.println("Input String: " + inputString);
System.out.println("Compressed Bytes: " + compressed.length);
System.out.println("Output String: " + outputString);
System.out.println("Compression Ratio: " + compressionRatio);
}
}
```
运行上述程序,将输出以下结果:
```
Input String: This is a test string for GZIP compression and decompression.
Compressed Bytes: 70
Output String: This is a test string for GZIP compression and decompression.
Compression Ratio: 0.5833333333333334
```
从输出结果可以看出,压缩后的字节数为70,压缩率为0.58左右。
阅读全文