下面的是测试代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class Test {
public static void main(String[] args) {
readFileAndWriteGZip();
unZipFile();
}
public static void readFileAndWriteGZip() {
try {
//打开需压缩文件作为文件输入流
FileInputStream fin = new FileInputStream("d:/test.txt");
//建立压缩文件输出流
FileOutputStream fout = new FileOutputStream("d:/test2.gzip");
//建立gzip压缩输出流
GZIPOutputStream gzout = new GZIPOutputStream(fout);
//设定读入缓冲区尺寸
byte[] buf = new byte[1024];
int num;
while ((num = fin.read(buf)) != -1)
{
gzout.write(buf,0,num);
}
gzout.close();
fout.close();
fin.close();
} catch (Exception ex) {
System.err.println(ex.toString());
}
}
public static void unZipFile() {
try {
//建立grip压缩文件输入流
FileInputStream fin = new FileInputStream("d:/test2.gzip");
//建立gzip解压工作流
GZIPInputStream gzin = new GZIPInputStream(fin);
//建立解压文件输出流
FileOutputStream fout = new FileOutputStream("d:/test2.txt");
byte[] buf=new byte[1024];
int num;
while ((num = gzin.read(buf,0,buf.length)) != -1)
{
fout.write(buf,0,num);
}
gzin.close();
fout.close();
fin.close();
} catch (Exception ex){
System.err.println(ex.toString());
}
}
}
测试通过。
参考: