綜述
在《 把多個文件打包壓縮成tar.gz文件並解壓的Java實現》中介紹了如何把文件壓縮車gz文件,這里介紹如何把文件壓縮成zip文件。支持如下方式的壓縮:
- 壓縮單個文件
- 壓縮文件夾下的所有文件
源碼
話不多說,直接上源代碼:
/**
* 壓縮指定文件夾中的所有文件,生成指定名稱的zip壓縮包
*
* @param sourcePath 需要壓縮的文件名稱列表(包含相對路徑)
* @param zipOutPath 壓縮后的文件名稱
**/
public static void batchZipFiles(String sourcePath, String zipOutPath) {
ZipOutputStream zipOutputStream = null;
WritableByteChannel writableByteChannel = null;
MappedByteBuffer mappedByteBuffer = null;
try {
zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutPath));
writableByteChannel = Channels.newChannel(zipOutputStream);
File file = new File(sourcePath);
for (File source : file.listFiles()) {
long fileSize = source.length();
//利用putNextEntry來把文件寫入
zipOutputStream.putNextEntry(new ZipEntry(source.getName()));
long read = Integer.MAX_VALUE;
int count = (int) Math.ceil((double) fileSize / read);
long pre = 0;
//由於一次映射的文件大小不能超過2GB,所以分次映射
for (int i = 0; i < count; i++) {
if (fileSize - pre < Integer.MAX_VALUE) {
read = fileSize - pre;
}
mappedByteBuffer = new RandomAccessFile(source, "r").getChannel()
.map(FileChannel.MapMode.READ_ONLY, pre, read);
writableByteChannel.write(mappedByteBuffer);
pre += read;
}
}
mappedByteBuffer.clear();
} catch (Exception e) {
log.error("Zip more file error, fileNames: " + sourcePath, e);
} finally {
try {
if (null != zipOutputStream) {
zipOutputStream.close();
}
if (null != writableByteChannel) {
writableByteChannel.close();
}
if (null != mappedByteBuffer) {
mappedByteBuffer.clear();
}
} catch (Exception e) {
log.error("Zip more file error, file names are:" + sourcePath, e);
}
}
}
小結
如果您在工作過程中遇到有關zip的壓縮問題,不妨在下方留言,大家一起來應對助您解決問題。如果感覺本文對您有幫助,請點贊並收藏。