Java实现Zip压缩文件操作的工具类
>> 项目源码可点击获取 (可作为Jar依赖包直接使用)
1、项目使用前,请进入rdc-bom目录下,执行mvn clean install命令
2、可根据需要进入rdc-module-file目录,执行mvn clean package命令
3、打包完成后,可直接引入Jar包使用或上传Maven私服使用。
public class ZipUtil {
static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 对压缩文件进行解压处理
*
* @param zipPath 待解压的压缩包路径,例如压缩包G:/abc.zip
* @param unzipDir 所有解压出来的文件的存放路径,例如G:/bde
*/
public static List<String> unzip(String zipPath, String unzipDir) {
if (zipPath == null || "".equals(zipPath) || unzipDir == null || "".equals(unzipDir)) {
return null;
}
File unzipDirFile = new File(unzipDir);
if (!unzipDirFile.exists() && !unzipDirFile.isDirectory()) {
unzipDirFile.mkdir();
}
File file = new File(zipPath);
if (file == null || !file.exists() || !file.isFile() || !file.canRead()) {
return null;
}
ZipFile zipFile = null;
try {
List<String> list = new ArrayList<String>();
zipFile = new ZipFile(zipPath);
System.out.println(zipFile.getName());
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enumeration.nextElement();
String filepath = unzipDir + "/" + entry.getName();
boolean result = writeToFile(zipFile, entry, new File(filepath));
if (result == false) {
return null;
}
list.add(filepath);
}
zipFile.close();
return list;
} catch (Exception e) {
e.printStackTrace();
logger.error("文件解压异常:", e);
} finally {
try {
if (null != zipFile) {
zipFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static boolean writeToFile(ZipFile zip, ZipEntry entry, File toFile) {
if (zip == null || entry == null || toFile == null) {
return false;
}
InputStream is = null;
FileOutputStream fos = null;
try {
if (!entry.isDirectory()) {
if (!toFile.exists()) {
toFile.getParentFile().mkdirs();
toFile.createNewFile();
}
is = zip.getInputStream(entry);
fos = new FileOutputStream(toFile);
int len = 0;
long size = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
size += len;
}
fos.flush();
if (entry.getSize() == size) {
return true;
}
} else {
if (!toFile.exists()) {
return toFile.mkdirs();
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/**
* @param srcDir 压缩文件夹路径
* @param basedir 压缩文件里的压缩路径(默认为“”)
* @param KeepDirStructure 是否保留原来的目录结构,
* true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<String> srcDir, String basedir, String outDir,
boolean KeepDirStructure) throws RuntimeException, Exception {
OutputStream out = new FileOutputStream(new File(outDir));
if (!StringUtils.isNotBlank(basedir)) {
basedir = "";
}
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
List<File> sourceFileList = new ArrayList<File>();
for (String dir : srcDir) {
File sourceFile = new File(dir);
sourceFileList.add(sourceFile);
}
compress(sourceFileList, basedir, zos, KeepDirStructure);
long end = System.currentTimeMillis();
logger.info("压缩完成,耗时:" + (end - start) + " ms,压缩路径:" + outDir);
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,
* true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos,
String name, boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
if (zos != null) {
zos.putNextEntry(new ZipEntry(name));
}
int len;
FileInputStream in = null;
try {
in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} 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 + "/" + file.getName(),
KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
private static void compress(List<File> sourceFileList, String basedir,
ZipOutputStream zos, boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
for (File sourceFile : sourceFileList) {
String name = sourceFile.getName();
if (sourceFile.isFile()) {
if (zos != null) {
zos.putNextEntry(new ZipEntry(basedir + name));
}
int len;
FileInputStream in = null;
try {
in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zos != null) {
zos.closeEntry();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
if (KeepDirStructure) {
if (zos != null) {
zos.putNextEntry(new ZipEntry(name + "/"));
}
try {
if (zos != null) {
zos.closeEntry();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
for (File file : listFiles) {
if (KeepDirStructure) {
compress(file, zos, name + "/" + file.getName(),
KeepDirStructure);
} else {
compress(file, zos, file.getName(),
KeepDirStructure);
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
unzip("D:\\tmp\\11.zip", "D:\\tmp");
}
}