package test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.log4j.Logger;
public class GZipUtil {
private static Logger log = Logger.getLogger(GZipUtil.class);
public GZipUtil() {
}
/**
* 对文件进行GZip压缩
*
*/
private byte[] gzipFile(String src) {
String fileName = "e:\\xml\\1.txt";
// String fileName = src;
// 压缩文件
FileInputStream zipin;
ByteArrayOutputStream bin = new ByteArrayOutputStream();
try {
zipin = new FileInputStream(fileName);
fileName = "e:\\xml\\1.txt.zip";
File zip = new File(fileName);
GZIPOutputStream zipout = new GZIPOutputStream(
new FileOutputStream(zip));
byte[] buffer = new byte[4096];
int bytes_read;
//从1.txt中读出放到buffer中
while ((bytes_read = zipin.read(buffer)) != -1) {
// 将buffer写到输入流,即写入1.txt.zip中
zipout.write(buffer, 0, bytes_read);
}
zipout.flush();
zipout.finish();
// 读取文件
FileInputStream fos = new FileInputStream(new File(fileName));
buffer = new byte[4096];
int flag = 0;
while ((flag = fos.read(buffer)) != -1) {
//将1.txt.zip写入到bin中
bin.write(buffer, 0, flag);
}
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bin.toByteArray();
}
/**
* 对文件进行GZip解压缩
* 将zipFileName解压成xmlFileName
*
*/
private void unGzipFile(byte[] in,String name) {
String zipFileName = "e:\\xml\\" + name + ".txt.zip";
String xmlFileName = "e:\\xml\\" + name + ".txt";
// String zipFileName1 = "e:\\xml\\" + name + "_1.txt.zip";
// String xmlFileName1 = "e:\\xml\\" + name + "_1.txt";
// 读取字节流
byte[] b = in;
int flag = 0;
if (b != null) {
// 读取ZIP文件
ByteArrayInputStream bin = new ByteArrayInputStream(b);
FileOutputStream fos;
try {
fos = new FileOutputStream(new File(zipFileName));
byte[] buffer = new byte[4096];
while ((flag = bin.read(buffer)) != -1) {
fos.write(buffer, 0, flag);
}
fos.close();
// 解压zip文件
FileOutputStream foszip = new FileOutputStream(
new File(xmlFileName));
GZIPInputStream zin = new GZIPInputStream(new FileInputStream(
new File(zipFileName)));
buffer = new byte[4096];
flag = 0;
while ((flag = zin.read(buffer)) != -1) {
foszip.write(buffer, 0, flag);
}
foszip.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
GZip压缩解压缩工具类
最新推荐文章于 2024-04-13 20:44:36 发布