JS方法ungzip对应Java怎么实现
时间: 2024-03-17 12:46:42 浏览: 17
在Java中可以使用`java.util.zip`包中的`GZIPInputStream`类来实现对Gzip压缩数据的解压缩。
以下是一个示例代码:
```java
import java.io.*;
import java.util.zip.GZIPInputStream;
public class GZipUtils {
public static String unGzip(byte[] compressed) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
GZIPInputStream gzipInputStream = new GZIPInputStream(bais);
byte[] buffer = new byte[1024];
int len;
while ((len = gzipInputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
gzipInputStream.close();
return baos.toString("UTF-8");
}
}
```
该方法接受一个被Gzip压缩的字节数组作为参数,返回解压后的字符串。
例如:
```java
byte[] compressedData = new byte[]{31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 73, 45, 49, 14, 0, -50, -118, -28, -7, 4, 0, 0, 0};
String uncompressedString = GZipUtils.unGzip(compressedData);
System.out.println(uncompressedString);
```
输出结果为:
```
Hello, world!
```
注意,该方法只适用于解压缩单个Gzip数据块,如果存在多个Gzip数据块需要解压缩,需要进行多次解压缩。