java针对单文件 zip压缩加密

package com.yukun;

/**
* 将excel打包生成zip文件,并且打开excel
文件的时候,需要输入密码,才可以打开.
作者 aa00aa00
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;

public class TestMailWithEncryptAttachment {

	/**
	 * 生成zip文件
	 * 
	 * @param srcfile
	 * @param zipFileName
	 * @param password
	 * @throws IOException
	 */
	public static void createZipFile(File srcfile, String zipFileName, String password) throws IOException {

		byte b[] = new byte[1024];
		ZipOutputStream zout = null;
		InputStream in = null;

		try {
			zout = new ZipOutputStream(new FileOutputStream(zipFileName));
			in = new FileInputStream(srcfile);

			String filename = srcfile.getName();// 取得文件名
			ZipEntry e = new ZipEntry(filename); // 压缩后不带路径
			zout.putNextEntry(e);

			int len = 0;
			while ((len = in.read(b)) != -1) {
				zout.write(b, 0, len);
			}

			zout.closeEntry();
			zout.flush();
			zout.close();

			in.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException io) {
			io.printStackTrace();
		} finally {
			if (zout != null) {
				try {
					zout.flush();
					zout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		TestMailWithEncryptAttachment.createProtectedZip(zipFileName, srcfile, password);
	}

	/**
	 * 生成加密的xls文件
	 * 
	 * @param zipFileName
	 * @param srcfile
	 * @param password
	 * @throws IOException
	 */
	public static void createProtectedZip(String zipFileName, File srcfile, String password) throws IOException {
		try {
			ZipFile zipFile = new ZipFile(zipFileName);

			ZipParameters parameters = new ZipParameters();
			parameters.setCompressionMethod(8);
			parameters.setCompressionLevel(5);
			parameters.setEncryptFiles(true);
			parameters.setEncryptionMethod(0);
			parameters.setPassword(password);
			zipFile.addFile(srcfile, parameters);
		} catch (ZipException e) {
			e.printStackTrace();
		}
	}

	

	public static void main(String[] args) throws IOException {
		// 压缩, 加密文件
		String zipFileName = "E:/resource.zip";
		String compressPassword = "1";
		File srcfile = new File("E:/文件名.doc");

		createZipFile(srcfile, zipFileName, compressPassword);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值