有時候需要批量下載文件,所以需要在后台將多個文件壓縮之后進行下載。
zip4j可以進行目錄壓縮與文件壓縮,同時可以加密壓縮。
common-compress只壓縮文件,沒有找到壓縮目錄的API。
1.zip4j的使用
pom地址:
<dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>1.3.2</version> </dependency>
工具類代碼:
package cn.qs.utils; import java.io.File; import java.util.ArrayList; import java.util.List; import org.springframework.util.StringUtils; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.util.Zip4jConstants; /** * 壓縮與解壓縮文件工具類 * * @author Administrator * */ public class ZipUtils { /** * 根據給定密碼壓縮文件(s)到指定目錄 * * @param destFileName * 壓縮文件存放絕對路徑 e.g.:D:/upload/zip/demo.zip * @param passwd * 密碼(可為空) * @param files * 單個文件或文件數組 * @return 最終的壓縮文件存放的絕對路徑,如果為null則說明壓縮失敗. */ public static String compress(String destFileName, String passwd, File... files) { ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 壓縮方式 parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 壓縮級別 if (!StringUtils.isEmpty(passwd)) { parameters.setEncryptFiles(true); parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式 parameters.setPassword(passwd.toCharArray()); } try { ZipFile zipFile = new ZipFile(destFileName); for (File file : files) { zipFile.addFile(file, parameters); } return destFileName; } catch (ZipException e) { e.printStackTrace(); } return null; } /** * 根據給定密碼壓縮文件(s)到指定位置 * * @param destFileName * 壓縮文件存放絕對路徑 e.g.:D:/upload/zip/demo.zip * @param passwd * 密碼(可為空) * @param filePaths * 單個文件路徑或文件路徑數組 * @return 最終的壓縮文件存放的絕對路徑,如果為null則說明壓縮失敗. */ public static String compress(String destFileName, String passwd, String... filePaths) { int size = filePaths.length; File[] files = new File[size]; for (int i = 0; i < size; i++) { files[i] = new File(filePaths[i]); } return compress(destFileName, passwd, files); } /** * 根據給定密碼壓縮文件(s)到指定位置 * * @param destFileName * 壓縮文件存放絕對路徑 e.g.:D:/upload/zip/demo.zip * @param passwd * 密碼(可為空) * @param folder * 文件夾路徑 * @return 最終的壓縮文件存放的絕對路徑,如果為null則說明壓縮失敗. */ public static String compressFolder(String destFileName, String passwd, String folder) { File folderParam = new File(folder); if (folderParam.isDirectory()) { File[] files = folderParam.listFiles(); return compress(destFileName, passwd, files); } return null; } /** * 根據所給密碼解壓zip壓縮包到指定目錄 * <p> * 如果指定目錄不存在,可以自動創建,不合法的路徑將導致異常被拋出 * * @param zipFile * zip壓縮包絕對路徑 * @param dest * 指定解壓文件夾位置 * @param passwd * 密碼(可為空) * @return 解壓后的文件數組 * @throws ZipException */ @SuppressWarnings("unchecked") public static File[] deCompress(File zipFile, String dest, String passwd) throws ZipException { // 1.判斷指定目錄是否存在 File destDir = new File(dest); if (destDir.isDirectory() && !destDir.exists()) { destDir.mkdir(); } // 2.初始化zip工具 ZipFile zFile = new ZipFile(zipFile); zFile.setFileNameCharset("UTF-8"); if (!zFile.isValidZipFile()) { throw new ZipException("壓縮文件不合法,可能被損壞."); } // 3.判斷是否已加密 if (zFile.isEncrypted()) { zFile.setPassword(passwd.toCharArray()); } // 4.解壓所有文件 zFile.extractAll(dest); List<FileHeader> headerList = zFile.getFileHeaders(); List<File> extractedFileList = new ArrayList<File>(); for (FileHeader fileHeader : headerList) { if (!fileHeader.isDirectory()) { extractedFileList.add(new File(destDir, fileHeader.getFileName())); } } File[] extractedFiles = new File[extractedFileList.size()]; extractedFileList.toArray(extractedFiles); return extractedFiles; } /** * 解壓無密碼的zip壓縮包到指定目錄 * * @param zipFile * zip壓縮包 * @param dest * 指定解壓文件夾位置 * @return 解壓后的文件數組 * @throws ZipException */ public static File[] deCompress(File zipFile, String dest) { try { return deCompress(zipFile, dest, null); } catch (ZipException e) { e.printStackTrace(); } return null; } /** * 根據所給密碼解壓zip壓縮包到指定目錄 * * @param zipFilePath * zip壓縮包絕對路徑 * @param dest * 指定解壓文件夾位置 * @param passwd * 壓縮包密碼 * @return 解壓后的所有文件數組 */ public static File[] deCompress(String zipFilePath, String dest, String passwd) { try { return deCompress(new File(zipFilePath), dest, passwd); } catch (ZipException e) { e.printStackTrace(); } return null; } /** * 無密碼解壓壓縮包到指定目錄 * * @param zipFilePath * zip壓縮包絕對路徑 * @param dest * 指定解壓文件夾位置 * @return 解壓后的所有文件數組 */ public static File[] deCompress(String zipFilePath, String dest) { try { return deCompress(new File(zipFilePath), dest, null); } catch (ZipException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { // 壓縮 // compressFolder("G:/sign.zip", "123456", "G:/sign"); // 解壓 deCompress("G:/sign.zip", "G:/unzip", "1234567"); } }
2.common-compress用法
只能壓縮與解壓縮文件,支持多種壓縮格式,比如:tar、zip、jar等格式,用法大致相同,參考官網即可。
pom地址:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.18</version> </dependency>
package cn.qs.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.ExecutionException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.IOUtils; public class ZipUtils { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { doUnzipTarfile(); } /** * 解壓縮tar文件 * * @throws FileNotFoundException * @throws IOException */ private static void doUnzipTarfile() throws FileNotFoundException, IOException { TarArchiveInputStream inputStream = new TarArchiveInputStream(new FileInputStream("G:/unzip/ttt.tar")); ArchiveEntry archiveEntry = null; while ((archiveEntry = inputStream.getNextEntry()) != null) { // h文件名稱 String name = archiveEntry.getName(); // 構造解壓出來的文件存放路徑 String entryFilePath = "G:/unzip/" + name; // 讀取內容 byte[] content = new byte[(int) archiveEntry.getSize()]; inputStream.read(content); // 內容拷貝 IOUtils.copy(inputStream, new FileOutputStream(entryFilePath)); } IOUtils.closeQuietly(inputStream); } /** * 解壓縮zip文件 * * @throws FileNotFoundException * @throws IOException */ private static void doUnzipZipfile() throws FileNotFoundException, IOException { ZipArchiveInputStream inputStream = new ZipArchiveInputStream(new FileInputStream("G:/unzip/ttt.zip")); ArchiveEntry archiveEntry = null; while ((archiveEntry = inputStream.getNextEntry()) != null) { // h文件名稱 String name = archiveEntry.getName(); // 構造解壓出來的文件存放路徑 String entryFilePath = "G:/unzip/" + name; // 讀取內容 byte[] content = new byte[(int) archiveEntry.getSize()]; inputStream.read(content); // 內容拷貝 IOUtils.copy(inputStream, new FileOutputStream(entryFilePath)); } IOUtils.closeQuietly(inputStream); } /** * 壓縮zip * * @throws IOException * @throws FileNotFoundException */ private static void doCompressZip() throws IOException, FileNotFoundException { ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("G:/unzip/ttt.zip")); zipOutput.setEncoding("GBK"); zipOutput.setUseZip64(Zip64Mode.AsNeeded); zipOutput.setMethod(ZipArchiveOutputStream.STORED); // 壓一個文件 ZipArchiveEntry entry = new ZipArchiveEntry("ttt.pdf"); zipOutput.putArchiveEntry(entry); FileInputStream fileInputStream = new FileInputStream(new File("G:/unzip/blank.pdf")); IOUtils.copyLarge(fileInputStream, zipOutput); IOUtils.closeQuietly(fileInputStream); zipOutput.closeArchiveEntry(); // 壓第二個文件 ZipArchiveEntry entry1 = new ZipArchiveEntry("killTomcat.bat"); zipOutput.putArchiveEntry(entry1); FileInputStream fileInputStream1 = new FileInputStream(new File("G:/unzip/springboot.log")); IOUtils.copyLarge(fileInputStream1, zipOutput); IOUtils.closeQuietly(fileInputStream1); zipOutput.closeArchiveEntry(); IOUtils.closeQuietly(zipOutput); } /** * 壓縮tar * * @throws IOException * @throws FileNotFoundException */ private static void doCompressTar() throws IOException, FileNotFoundException { TarArchiveOutputStream tarOut = new TarArchiveOutputStream(new FileOutputStream("G:/unzip/ttt.tar")); // 壓一個文件 TarArchiveEntry entry = new TarArchiveEntry("ttt.pdf"); File file = new File("G:/unzip/ttt.pdf"); entry.setSize(file.length()); tarOut.putArchiveEntry(entry); FileInputStream fileInputStream = new FileInputStream(file); IOUtils.copyLarge(fileInputStream, tarOut); IOUtils.closeQuietly(fileInputStream); tarOut.closeArchiveEntry(); // 壓第二個文件 TarArchiveEntry entry1 = new TarArchiveEntry("killTomcat.bat"); File file2 = new File("G:/unzip/killTomcat.bat"); entry1.setSize(file2.length()); tarOut.putArchiveEntry(entry1); FileInputStream fileInputStream1 = new FileInputStream(file2); IOUtils.copyLarge(fileInputStream1, tarOut); IOUtils.closeQuietly(fileInputStream1); tarOut.closeArchiveEntry(); IOUtils.closeQuietly(tarOut); } }