java 解压gz文件
时间: 2024-03-31 08:29:43 浏览: 15
在Java中解压.gz文件可以使用GZIPInputStream类来实现。下面是一个简单的示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class GzipFileExtractor {
public static void main(String[] args) {
String sourceFile = "compressed.gz";
String destFile = "uncompressed.txt";
try {
FileInputStream fis = new FileInputStream(sourceFile);
GZIPInputStream gzis = new GZIPInputStream(fis);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int len;
while ((len = gzis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
gzis.close();
fos.close();
System.out.println("解压成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码中,我们首先创建一个`FileInputStream`来读取压缩文件,然后使用`GZIPInputStream`来解压缩数据。接着,我们创建一个`FileOutputStream`来写入解压后的数据。通过循环读取和写入数据,最后关闭输入输出流即可完成解压操作。