public class GzipFileCompression {
public String compression(String fileDir) throws Exception {
File file = new File(fileDir);
String desc = file.getAbsolutePath();
if (file.exists()) {
desc = file.getParent() + File.separator + file.getName() + ".gz";
FileInputStream fin = new FileInputStream(fileDir);
FileOutputStream out = new FileOutputStream(desc);
GZIPOutputStream gos = new GZIPOutputStream(out);
int count;
byte data[] = new byte[1024];
while ((count = fin.read(data, 0, 1024)) != -1) {
gos.write(data, 0, count);
}
gos.finish();
gos.flush();
gos.close();
fin.close();
}
return desc;
}
public void decompression(String fileDir) throws Exception {
File gzipFile = new File(fileDir);
<span style="white-space:pre"> </span>File parentDir = gzipFile.getParentFile();
<span style="white-space:pre"> </span>String filename = gzipFile.getName();
<span style="white-space:pre"> </span>String desc = parentDir + File.separator +filename.substring(0, filename.lastIndexOf("."));
FileInputStream fin = new FileInputStream(fileDir);
BufferedInputStream in = new BufferedInputStream(fin);
FileOutputStream out = new FileOutputStream(desc);
GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
final byte[] buffer = new byte[1024];
int n = 0;
while (-1 != (n = gzIn.read(buffer))) {
out.write(buffer, 0, n);
}
out.close();
gzIn.close();
}
}
Java实现Gzip的压缩和解压
最新推荐文章于 2024-07-10 14:27:13 发布