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);
}
}