import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @description: 压缩工具类
* @author: wujie
* @create: 2020-08-28 09:49
**/
@Slf4j
public class ZipUtils {
/**
* 文件夹压缩成zip
*
* @param zipFilePath
* @param filePath
*/
public static void zipFileChannel(String zipFilePath, String filePath) {
long beginTime = System.currentTimeMillis();
File zipFile = new File(zipFilePath);
try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
WritableByteChannel writableByteChannel = Channels.newChannel(zipOut)) {
File path = new File(filePath);
File[] files = path.listFiles();
FileChannel fileChannel;
for (File file : files) {
fileChannel = new FileInputStream(file).getChannel();
zipOut.putNextEntry(new ZipEntry(file.getName()));
fileChannel.transferTo(0, file.length(), writableByteChannel);
}
long endTime = System.currentTimeMillis();
log.info("File compression complete. Time consuming: {}ms. File size:{}", endTime - beginTime, CommonUtils.formatBytes(zipFile.length()));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
zipFileChannel("D:\\Downloads\\tempFile\\a.zip", "D:\\Downloads\\tempFile\\test");
}
}
/**
* 字节转换,计算文件大小
*
* @param size
* @return
*/
public static String formatBytes(long size) {
int GB = 1024 * 1024 * 1024;
int MB = 1024 * 1024;
int KB = 1024;
DecimalFormat df = new DecimalFormat("0.00");
String resultSize = "";
if (size / GB >= 1) {
resultSize = df.format(size / (float) GB) + "GB";
} else if (size / MB >= 1) {
resultSize = df.format(size / (float) MB) + "MB";
} else if (size / KB >= 1) {
resultSize = df.format(size / (float) KB) + "KB";
} else {
resultSize = size + "B";
}
return resultSize;
}