Java基础-实现zip解压
可实现: ⽂件、⽂件夹的解压缩操作
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ⽂件压缩⼯具类
*/
public class ZipUtil {
private static final int BUFFER_SIZE = 2 * 1024;
走出非洲 下载
/**
* 是否保留原来的⽬录结构
* true:  保留⽬录结构;
* false: 所有⽂件跑到压缩包根⽬录下(注意:不保留⽬录结构可能会出现同名⽂件,会压缩失败)
*/
private static final boolean KeepDirStructure = true;
private static final Logger log = Logger(ZipUtil.class);
public static void main(String[] args) {
try {
toZip("E:/app1", "E:/app.zip",true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 压缩成ZIP
* @param srcDir        压缩⽂件/⽂件夹路径
* @param outPathFile    压缩⽂件/⽂件夹输出路径+⽂件名 D:/xx.zip
* @param isDelSrcFile  是否删除原⽂件: 压缩前⽂件
*/
public static void toZip(String srcDir, String outPathFile,boolean isDelSrcFile) throws Exception {
long start = System.currentTimeMillis();
FileOutputStream out = null;
ZipOutputStream zos = null;
try {
out = new FileOutputStream(new File(outPathFile));
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
if(!ists()){
throw new Exception("需压缩⽂件或者⽂件夹不存在");
}
compress(sourceFile, zos, Name());
if(isDelSrcFile){
delDir(srcDir);
}
log.info("原⽂件:{}. 压缩到:{}完成. 是否删除原⽂件:{}. 耗时:{}ms. ",srcDir,outPathFile,isDelSrcFile,System.currentTimeMillis()-start);  } catch (Exception e) {
<("zip error from ZipUtils: {}. ",e.getMessage());
throw new Exception("zip error from ZipUtils");
throw new Exception("zip error from ZipUtils");
} finally {
try {
if (zos != null) {zos.close();}
if (out != null) {out.close();}
} catch (Exception e) {}
}
}
/**
* 递归压缩⽅法
* @param sourceFile 源⽂件
* @param zos zip输出流
* @param name 压缩后的名称
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name)  throws Exception {
姜瑞佳
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
zos.putNextEntry(new ZipEntry(name));
黄家驹女友唱海阔天空
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
if (KeepDirStructure) {
zos.putNextEntry(new ZipEntry(name + "/"));
zos.closeEntry();
}
} else {
for (File file : listFiles) {
if (KeepDirStructure) {
compress(file, zos, name + "/" + Name());
} else {
compress(file, zos, Name());
}
}
}
}
}
/**
* 解压⽂件到指定⽬录
*/
@SuppressWarnings({ "rawtypes", "resource" })
public static void unZipFiles(String zipPath, String descDir) throws IOException {  log.info("⽂件:{}. 解压路径:{}. 解压开始.",zipPath,descDir);
long start = System.currentTimeMillis();
我代表月亮消灭你们try{
File zipFile = new File(zipPath);
if(!ists()){
throw new IOException("需解压⽂件不存在.");
}
File pathFile = new File(descDir);
if (!ists()) {
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for (Enumeration entries = ies(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) Element();
ZipEntry entry = (ZipEntry) Element();
String zipEntryName = Name();
InputStream in = InputStream(entry);
String outPath = (descDir + File.separator + zipEntryName).replaceAll("\\*", "/");
放手去爱不要逃
// 判断路径是否存在,不存在则创建⽂件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!ists()) {
file.mkdirs();
}
/
/ 判断⽂件全路径是否为⽂件夹,如果是上⾯已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
吻和泪 周子寒
// 输出⽂件路径信息
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
log.info("⽂件:{}. 解压路径:{}. 解压完成. 耗时:{}ms. ",zipPath,descDir,System.currentTimeMillis()-start);
}catch(Exception e){
log.info("⽂件:{}. 解压路径:{}. 解压异常:{}. 耗时:{}ms. ",zipPath,descDir,e,System.currentTimeMillis()-start);  throw new IOException(e);
}
}
// 删除⽂件或⽂件夹以及⽂件夹下所有⽂件
public static void delDir(String dirPath) throws IOException {
log.info("删除⽂件开始:{}.",dirPath);
long start = System.currentTimeMillis();
try{
File dirFile = new File(dirPath);
if (!ists()) {
return;
}
if (dirFile.isFile()) {
dirFile.delete();
return;
}
File[] files = dirFile.listFiles();
if(files==null){
return;
}
for (int i = 0; i < files.length; i++) {
delDir(files[i].toString());
}
dirFile.delete();
log.info("删除⽂件:{}. 耗时:{}ms. ",dirPath,System.currentTimeMillis()-start);
}catch(Exception e){
log.info("删除⽂件:{}. 异常:{}. 耗时:{}ms. ",dirPath,e,System.currentTimeMillis()-start);
throw new IOException("删除⽂件异常.");
}
}
}