用Java压缩文件(夹)

Java压缩文件/文件夹

应用场景:
备份文件,然而,某网盘不让上传大文件,

那就一个文件夹一个文件夹地压缩,再上传。

手动压缩太麻烦,故用代码压缩之。

package com.ah.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 参考:https://www.cnblogs.com/daofu/p/16195729.html
 */
public class AhZipUtils {
	public static void doCompress(String srcFilePath) {
		String date = AhTimeUtils.getYMD();
		doCompress(srcFilePath, srcFilePath + "_" + date + ".zip");
	}

	public static void doCompress(String srcFilePath, String zipFilePath) {
		File srcFile = new File(srcFilePath);
		if (!srcFile.exists()) {
			AhCommonUtils.printlog("需要压缩的文件(夹)不存在:" + srcFilePath);
			return;
		}
		File zipFile = new File(zipFilePath);
		AhFileUtils.deletePath(zipFilePath);
		long showTime1_start = AhCommonUtils.showTime1_start();
		System.out.println("开始压缩:" + srcFilePath);
		doCompress(srcFile, zipFile);
		AhCommonUtils.showTime2_end(showTime1_start);
		System.out.println("压缩完成:" + zipFilePath);
	}

	/**
	 * 文件压缩
	 * 
	 * @param srcFile 目录或者单个文件
	 * @param zipFile 压缩后的ZIP文件
	 */
	private static void doCompress(File srcFile, File zipFile) {

		try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
			String dir = "";
			doCompress(srcFile, out, dir);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param inFile
	 * @param out
	 * @param dir:解压出来的的文件,会放在这个文件夹中
	 * @throws IOException
	 */
	private static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
		if (inFile.isDirectory()) {
			File[] files = inFile.listFiles();
			if (files != null && files.length > 0) {
				for (File file : files) {
					String name = inFile.getName();
					if (!"".equals(dir)) {
						name = dir + "/" + name;
					}
					doCompress(file, out, name);
				}
			}
		} else {
			doZip(inFile, out, dir);
		}
	}

	private static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
		String entryName = null;
		if (!"".equals(dir)) {
			entryName = dir + "/" + inFile.getName();
		} else {
			entryName = inFile.getName();
		}
		ZipEntry entry = new ZipEntry(entryName);
		out.putNextEntry(entry);
		int len = 0;
		byte[] buffer = new byte[1024];
		FileInputStream fis = new FileInputStream(inFile);
		while ((len = fis.read(buffer)) > 0) {
			out.write(buffer, 0, len);
			out.flush();
		}
		out.closeEntry();
		fis.close();
	}

	/**
	 * 正式使用,非测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		AhZipUtils.doCompress("/Users/Documents/AH_Code/AhProjData1");
        AhZipUtils.doCompress("/Users/Documents/AH_Code/AhProjData2");
	}
}
posted @ 2023-01-24 17:21  虎老狮  阅读(1532)  评论(0编辑  收藏  举报