GZ压缩文件解压,直接上代码:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
/**
* 解压.gz文件
* @author www
*
*/
public class Gzip {
public static final int BUFFER = 1024;
public static final String EXT = ".gz";
public static void main(String[] args) {
try {
deCompress("文件路径");
} catch (Exception e) {
throw new RuntimeException("解压文件失败!", e);
}
}
/**
* 文件解压缩
* @param file
* @throws Exception
*/
public static void deCompress(String fileName) throws Exception {
File file = new File(fileName);
System.out.println(file);
decompressFile(file, false);
}
/**
* 文件解压缩,是否删除原文件
* @param file
* @param delete
* @throws Exception
*/
public static void decompressFile (File file,boolean delete) throws Exception{
FileOutputStream fos = new FileOutputStream(file);
FileInputStream fis = new FileInputStream(file.getPath().replace(EXT, ""));
decompress(fis, fos);
fis.close();
fos.flush();
fos.close();
if(delete) {
file.delete();
}
}
/**
* 数据解压缩
* @param is
* @param os
* @throws Exception
*/
public static void decompress(InputStream is, OutputStream os) throws Exception {
GZIPInputStream gis = new GZIPInputStream(is);
int count;
byte[] data = new byte[1024];
while((count = gis.read(data,0,BUFFER))!=-1) {
os.write(data,0,count);
}
}
}