java 壓縮成zip文件、解壓zip文件(可設置密碼)


1.情景展示

  java實現將文件夾進行壓縮打包的功能及在線解壓功能

2.解決方案

  方式一:壓縮、解壓zip

  准備工作:slf4j-api.jar

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

  如果不需要日志記錄,則可以把log去掉。

  導入

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

  壓縮成zip

/**
 * 文件壓縮、解壓工具類
 */
public class ZipUtils {
	private static final int BUFFER_SIZE = 2 * 1024;
	/**
	 * 是否保留原來的目錄結構
	 * true:  保留目錄結構;
	 * false: 所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
	 */
	private static final boolean KeepDirStructure = true;
	private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
	public static void main(String[] args) {
		try {
//			toZip("D:\\apache-maven-3.5.3\\maven中央倉庫-jar下載", "D:\\apache-maven-3.5.3\\maven中央倉庫-jar下載.zip",true);
			unZipFiles("D:\\\\apache-maven-3.5.3\\\\maven中央倉庫-jar下載.zip","D:\\apache-maven-3.5.3\\maven中央倉庫-jar下載");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 壓縮成ZIP
	 * @param srcDir         壓縮 文件/文件夾 路徑
	 * @param outPathFile    壓縮 文件/文件夾 輸出路徑+文件名 D:/xx.zip
	 * @param isDelSrcFile   是否刪除原文件: 壓縮前文件
	 */
	public static void toZip(String srcDir, String outPathFile,boolean isDelSrcFile) throws Exception {
		long start = System.currentTimeMillis();
		FileOutputStream out = null; 
		ZipOutputStream zos = null;
		try {
			out = new FileOutputStream(new File(outPathFile));
			zos = new ZipOutputStream(out);
			File sourceFile = new File(srcDir);
			if(!sourceFile.exists()){
				throw new Exception("需壓縮文件或者文件夾不存在");
			}
			compress(sourceFile, zos, sourceFile.getName());
			if(isDelSrcFile){
				delDir(srcDir);
			}
			log.info("原文件:{}. 壓縮到:{}完成. 是否刪除原文件:{}. 耗時:{}ms. ",srcDir,outPathFile,isDelSrcFile,System.currentTimeMillis()-start);
		} catch (Exception e) {
			log.error("zip error from ZipUtils: {}. ",e.getMessage());
			throw new Exception("zip error from ZipUtils");
		} finally {
			try {
				if (zos != null) {zos.close();}
				if (out != null) {out.close();}
			} catch (Exception e) {}
		}
	}

	/**
	 * 遞歸壓縮方法
	 * @param sourceFile 源文件
	 * @param zos zip輸出流
	 * @param name 壓縮后的名稱
	 */
	private static void compress(File sourceFile, ZipOutputStream zos, String name)
			throws Exception {
		byte[] buf = new byte[BUFFER_SIZE];
		if (sourceFile.isFile()) {
			zos.putNextEntry(new ZipEntry(name));
			int len;
			FileInputStream in = new FileInputStream(sourceFile);
			while ((len = in.read(buf)) != -1) {
				zos.write(buf, 0, len);
			}
			zos.closeEntry();
			in.close();
		} 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());
					} else {
						compress(file, zos, file.getName());
					}
				}
			}
		}
	}
	
	// 刪除文件或文件夾以及文件夾下所有文件
	public static void delDir(String dirPath) throws IOException {
		log.info("刪除文件開始:{}.",dirPath);
		long start = System.currentTimeMillis();
		try{
			File dirFile = new File(dirPath);
			if (!dirFile.exists()) {
				return;
			}
			if (dirFile.isFile()) {
				dirFile.delete();
				return;
			}
			File[] files = dirFile.listFiles();
			if(files==null){
				return;
			}
			for (int i = 0; i < files.length; i++) {
				delDir(files[i].toString());
			}
			dirFile.delete();
			log.info("刪除文件:{}. 耗時:{}ms. ",dirPath,System.currentTimeMillis()-start);
		}catch(Exception e){
			log.info("刪除文件:{}. 異常:{}. 耗時:{}ms. ",dirPath,e,System.currentTimeMillis()-start);
			throw new IOException("刪除文件異常.");
		}
	}
}

  將zip進行解壓

/**
 * 解壓文件到指定目錄
 * @explain
 * @param zipPath 壓縮包的絕對完整路徑
 * @param outDir 解壓到哪個地方
 * @throws IOException
 */
@SuppressWarnings({ "rawtypes", "resource" })
public static void unZipFiles(String zipPath, String outDir) throws IOException {
    log.info("文件:{}. 解壓路徑:{}. 解壓開始.",zipPath,outDir);
    long start = System.currentTimeMillis();
    try{
        File zipFile = new File(zipPath);
        System.err.println(zipFile.getName());
        if(!zipFile.exists()){
            throw new IOException("需解壓文件不存在.");
        }
        File pathFile = new File(outDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
        for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            System.err.println(zipEntryName);
            InputStream in = zip.getInputStream(entry);
            String outPath = (outDir + File.separator + zipEntryName).replaceAll("\\*", "/");
            System.err.println(outPath);
            // 判斷路徑是否存在,不存在則創建文件路徑
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判斷文件全路徑是否為文件夾,如果是上面已經上傳,不需要解壓
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 輸出文件路徑信息
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        log.info("文件:{}. 解壓路徑:{}. 解壓完成. 耗時:{}ms. ",zipPath,outDir,System.currentTimeMillis()-start);
    }catch(Exception e){
        log.info("文件:{}. 解壓路徑:{}. 解壓異常:{}. 耗時:{}ms. ",zipPath,outDir,e,System.currentTimeMillis()-start);
        throw new IOException(e);
    }
}

  測試

public static void main(String[] args) {
    try {
        // 壓縮
        toZip("D:\\apache-maven-3.5.3\\maven中央倉庫-jar下載", "D:\\apache-maven-3.5.3\\maven中央倉庫-jar下載.zip",true);
        // 解壓
        //unZipFiles("D:\\\\apache-maven-3.5.3\\\\maven中央倉庫-jar下載.zip","D:\\apache-maven-3.5.3");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  方式二:壓縮成zip可設密碼

  所需jar包:zip4j_1.3.1.jar

package base.web.tools;

import java.io.FileNotFoundException;

import org.apache.commons.lang.StringUtils;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;


/**
 * <ul>
 * <li>支持多層次目錄ZIP壓縮的工具</li>
 * <li>用法 :</li>
 * <li>1.普通壓縮, Zipper.packageFolder(folder, target);</li>
 * <li>2.加密碼的壓縮 , Zipper.packageFolderWithPassword(folder, target, password);</li>
 * <li>參數說明:</li>
 * <ol>
 * <li>folder 待壓縮的目錄</li>
 * <li>target 目標文件路徑</li>
 * </ol>
 * </ul>
 */
public class Zipper {

	/**
	 * 壓縮文件夾
	 * @expalin 如果已經存在相同的壓縮包,則會覆蓋之前的壓縮包
	 * @param folder 要打包的文件夾的磁盤路徑
	 * 比如,D:\\aa\\bb
	 * @param target 存放打包后的壓縮包的磁盤路徑
	 * 構成:路徑+壓縮包名稱.后綴名
	 * 比如,D:\\aa\\bb.zip
	 * @throws ZipException
	 */
	public static void packageFolder(String folder, String target) throws ZipException {
		packageFolderWithPassword(folder, target, null);
	}
	
	public static void packageFolderWithPassword(String folder, String target, String password) throws ZipException{
		ZipFile zip = new ZipFile(target);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
		// 加密
		if(StringUtils.isNotBlank(password)){
			parameters.setEncryptFiles(true);
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
			parameters.setPassword(password);
		}
		
		zip.addFolder(folder, parameters);
	}

	public static void main(String[] args) throws FileNotFoundException {
		try {
			packageFolder("D:\\aa\\bb", "D:\\aa\\bb.zip");
		} catch (ZipException e) {
			e.printStackTrace();
		}
	}
}

  

寫在最后

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM