日期:2014-05-20 浏览次数:20873 次
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Zip工具类
*/
public class ZipUtil {
private static final String PATH_SEP = "\\";
public static final int BUFFER = 2048;
/**
* 解压缩zip文件
*
* @param zipFileName
* zip文件路径
* @param fileExtractPath
* 解压缩目录
* @param projectName
* 工程名
* @throws IOException
*/
public static File unzipFilesToPath(String zipFileName,
String fileExtractPath, String projectName) {
//解压前 先删除目录中存在的目录
if(projectName != null && !"".equals(projectName)){
File dir = new File(fileExtractPath + PATH_SEP + projectName);
if(dir.exists()){
deleteFile(dir);
}
}
FileInputStream fis = null;
ZipInputStream zis = null;
try {
fis = new FileInputStream(zipFileName);
zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File resultFile =null;
int i=0;
while ((entry = zis.getNextEntry()) != null) {
int count;
byte[] data = new byte[BUFFER];
String fopath = fileExtractPath + PATH_SEP + projectName
+ PATH_SEP + entry.getName();
if (entry.isDirectory()) {
if(i==0){
resultFile = new File(fileExtractPath + PATH_SEP + projectName
+ PATH_SEP + entry.getName());
}
i++;
new File(fopath).mkdirs();
continue;
}
final FileOutputStream fos = new FileOutputStream(fopath);
final BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
i++;
}
return resultFile;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@SuppressWarnings("resource")
public static File unzipFilesToPathThrowException(String zipFileName,
String fileExtractPath, String projectName) throws IOException {