ZIP工具类
package com.jbit.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Component
public class ZipUtils {
private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
public void createZip(String sourcePath, String zipPath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
writeZip(new File(sourcePath), "", zos);
} catch (FileNotFoundException e) {
log.error("failed to create zip file!", e);
} finally {
try {
if (zos != null) {
log.info("Zip file created successfully! The path:{}",zipPath);
zos.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
log.error("failed to create zip file!", e);
}
}
}
private void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.exists()) {
if (file.isDirectory()) {
if(parentPath.length() != 0){
parentPath += File.separator;
try {
zos.putNextEntry(new ZipEntry(parentPath));
} catch (IOException e) {
log.error("failed to create zip file!",e);
}
}
File[] files = file.listFiles();
for (File f : files) {
writeZip(f, parentPath + f.getName(), zos);
}
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(parentPath));
byte[] content = new byte[1024];
int len;
while ((len = fis.read(content)) != -1) {
zos.write(content, 0, len);
zos.flush();
}
} catch (FileNotFoundException e) {
log.error("failed to create zip file!",e);
} catch (IOException e) {
log.error("failed to create zip file!",e);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
log.error("failed to create zip file!",e);
}
}
}
}
}
public void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
deleteFile(f);
}
}
file.delete();
}
}
}