您的位置:首页 > 编程语言 > Java开发

JAVA,导出CSV,设最大行数限制,使用winzipaes压缩成带密码的zip文件

2011-10-21 11:22 429 查看
由于工作需要,导出CSV功能,太大的话要分成多个,并且导出文件要压缩成带密码的zip。

JAVA本身的ZIP输入输出流是支持多个文件的,但是没有设置密码功能。

网上搜索了很久,最后选择使用开源的winzipaes。

地址 http://code.google.com/p/winzipaes/

下载它的source,自己编译生成jar。在编译时,要用到bcprov-jdk jar包,到下面的网页里下载。

目前的winzipaes_src_20110911.zip,官网推荐使用bcprov-jdk15-146.jar

http://www.bouncycastle.org/latest_releases.html

1. 使用示例(源码里的例子,没测试过)

压缩

File inFile;
File outFile;
...
AESEncrypter encrypter = new AESEncrypterBC();
AesZipFileEncrypter enc = new AesZipFileEncrypter(outFile,encrypter);
try {
enc.add(inFile, password);
} finally {
enc.close();
}


解压

AesZipFileDecrypter zipFile = new AesZipFileDecrypter( new File("doc/zipSpecificationAes.zip"), new AESDecrypterBC() );
ExtZipEntry entry = zipFile.getEntry( "zipSpecification.txt" );
zipFile.extractEntryWithTmpFile( entry, new File("doc/zipSpecification.txt"), "foo" );


2. 压缩多个文件时,有两个方法

(1) 预先把多个文件压缩成zip,使用enc.addAll(inZipFile, password);方法。

(2)循环调用enc.add(inFile, password);,每次用相同的密码

3. 压缩包里的path

使用add(File file, String password)方法,会把file的路径(绝对路径或相对路径,有创建file时决定)自动作为zip里的path。

不想要路径或者想自己指定的话,使用add(File file, String password)方法。

4. 不用inFile,通过流创建(省却创建临时文件,我就是用这个)

使用add(String name, InputStream is, String password)方法。

5. 我的导出CSV并带密码压缩代码(大体样子,不完全)

List<DTO> dtoList = getData();
OutputStream out = null;
AesZipFileEncrypter enc = null;
byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
try {
out = response.getOutputStream();
enc = new AesZipFileEncrypter(out, new AESEncrypterBC());
int totalRowNum = dtoList.size();
int rowNum = 0;
final int MAX_ROW_NUM = 1000;
int fileNum = 0;
String csvData = "";

for (DTO dto : dtoList)  {
rowNum++;

// edit csv data
...

if  (rowNum  % MAX_ROW_NUM == 0  ||
rowNum == totalRowNum)	 {
// excel打开UTF乱码的对应
byte[] csvDataBytes = csvData.getBytes();
byte[] outputDataBytes = new byte[csvDataBytes.length + bom.length];
System.arraycopy(bom, 0, outputDataBytes , 0, bom.length);
System.arraycopy(csvDataBytes , 0, outputDataBytes , bom.length, csvDataBytes .length);

DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(outputDataBytes ));

// 添加到zip
enc.add((++fileNum) + ".csv", dataInputStream, “123456”);

if (rowNum < totalRowNum) {
csvData = "";
}
}
}

out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (enc != null) {enc.close();}
if (out != null) {out.close();}
}


遗留问题(有时间研究一下代码看看有什么原因和解决方法):

1. 好像没有不设密码的方法

2. 压缩包里的文件名会出现乱码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: