package mms;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipFile;
import java.util.Enumeration;
public class zipAndUnzip {
static final int BUFFER = 8192;
//压缩
int zip(File srcFiles[],String outZipFile){
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(outZipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < srcFiles.length; i++) {
FileInputStream fi = new FileInputStream(srcFiles[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(srcFiles[i].getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
fi.close();
origin.close();
}
out.close();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
//解压
//srcZipFiles 压缩文件路径
//outFilePath 解压文件输出路径
int unzip(String srcZipFiles,String outFilePath){
System.out.println("srcZipFiles:"+srcZipFiles);
System.out.println("outFilePath:"+outFilePath);
ZipFile zipFile = new ZipFile(srcZipFiles);
Enumeration<? extends ZipEntry> emu = zipFile.entries();
String unzip_dir = srcZipFiles.substring(srcZipFiles.lastIndexOf("/")+1,srcZipFiles.lastIndexOf(".") );
String new_dir = "";
File file = null;
boolean flag = false;
while(emu.hasMoreElements()){
ZipEntry entry = (ZipEntry)emu.nextElement();
System.out.println("entry.getName():"+entry.getName());
if(entry.getName().indexOf("/")>=0){
new_dir = entry.getName().substring(0,entry.getName().lastIndexOf("/"));
}else{
new_dir = unzip_dir;
flag = true;
}
System.out.println("new_dir:"+new_dir);
//会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。
if (entry.isDirectory())
{
if(!flag){
new File(outFilePath + entry.getName().replace(new_dir,unzip_dir)).mkdirs();
}else{
new File(outFilePath + new_dir+"/"+entry.getName()).mkdirs();
}
//new File(outFilePath + entry.getName()).mkdirs();
continue;
}
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
if(!flag){
file = new File(outFilePath + entry.getName().replace(new_dir,unzip_dir));
}else{
file = new File(outFilePath + new_dir+"/"+entry.getName());
}
//File file = new File(outFilePath + entry.getName());
//加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件
//而这个文件所在的目录还没有出现过,所以要建出目录来。
File parent = file.getParentFile();
if(parent != null && (!parent.exists())){
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1)
{
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
zipFile.close();
return 0;
}
}