import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException, Exception {
String srcPath = "E:\\zhanglong.zip";
String dstPath = "E:\\zhanglong";
Decompression.unZip(srcPath, dstPath);
}
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Decompression {
//解压gzip数据
public static String unGzip(InputStream is){
String result = null;
GZIPInputStream in = null;
ByteArrayOutputStream arrayOutputStream = null;
try {
in = new GZIPInputStream(is);
arrayOutputStream = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[Constant.BUFFER];
while ((len = in.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
result = new String(arrayOutputStream.toByteArray(), Constant.UTF);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(in != null){
in.close();
}
if(arrayOutputStream != null){
arrayOutputStream.close();
}
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
//压缩gzip数据
public static byte[] gzip(String data, String charset) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes(charset));
gzip.finish();
gzip.close();
b = bos.toByteArray();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
/**************************************************/
//解压zip压缩包
public static boolean unZip(String srcPath, String dstPath) {
boolean isUnzipSuccess = false;
boolean isDstFormat = false;
int count = -1;
int index = -1;
File dstFolder = new File(dstPath);
if(!dstFolder.exists()) dstFolder.mkdirs();
FileInputStream fis = null;
ZipInputStream zis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
ZipEntry entry = null;
fis = new FileInputStream(srcPath);
zis = new ZipInputStream(new BufferedInputStream(fis));
while ((entry = zis.getNextEntry()) != null) {
byte[] data = new byte[Constant.BUFFER * 10];
String temp = entry.getName();
isDstFormat = isDstFormat(temp);
if(!isDstFormat)
continue;
index = temp.lastIndexOf("/");
if (index >
-1) temp = temp.substring(index + 1);
temp = dstPath + File.separator + temp;
File file = new File(temp);
file.createNewFile();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, Constant.BUFFER * 10);
while ((count = zis.read(data, 0, Constant.BUFFER * 10)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
}
isUnzipSuccess = true;