- 直接上代码:
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class JieyaTar {
public static void main(String[] args) {
JieyaTar jieya = new JieyaTar();
jieya.yasuoTarToGZ();
}
private void yasuoTarToGZ() {
File tarFile = new File("f:\\wjh.tar");
File gzFile = new File(tarFile + ".gz");
GZIPOutputStream out = null;
InputStream in = null;
boolean boo = false;
try{
in = new FileInputStream(tarFile);
out = new GZIPOutputStream(new FileOutputStream(gzFile),1024 * 2);
byte b[] = new byte[1024 * 2];
int length = 0;
while( (length = in.read(b)) != -1 ){
out.write(b,0,length);
}
boo = true;
}catch(Exception ex){
throw new RuntimeException("压缩文件失败",ex);
}finally{
try{
if(out!=null)
out.close();
if(in!=null)
in.close();
}catch(IOException ex){
throw new RuntimeException("关闭流出现异常",ex);
}finally{
if(!boo){
tarFile.delete();
if(gzFile.exists())
gzFile.delete();
}
}
}
}
- 压缩结果: