ITeye博客

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

lvjun106 · 2015-05-03 11:27 · JAVA · 开源软件 · Markdown

[转:http://blog.csdn.net/lian_zhihui1984/article/details/6893119]

由于工作需要,导出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. 使用示例(源码里的例子,没测试过)

压缩

 

[java] view plaincopy

 

  1. File inFile;
  2. File outFile;
  3. ...
  4. AESEncrypter encrypter = new AESEncrypterBC();
  5. AesZipFileEncrypter enc = new AesZipFileEncrypter(outFile,encrypter);
  6. try {
  7. enc.add(inFile, password);
  8. } finally {
  9. enc.close();
  10. }

 

 

解压

 

[java] view plaincopy

 

  1. AesZipFileDecrypter zipFile = new AesZipFileDecrypter( new File("doc/zipSpecificationAes.zip"), new AESDecrypterBC() );
  2. ExtZipEntry entry = zipFile.getEntry( "zipSpecification.txt" );
  3. 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并带密码压缩代码(大体样子,不完全)

 

[java] view plaincopy

 

  1. List<DTO> dtoList = getData();
  2. OutputStream out = null;
  3. AesZipFileEncrypter enc = null;
  4. byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
  5. try {
  6. out = response.getOutputStream();
  7. enc = new AesZipFileEncrypter(out, new AESEncrypterBC());
  8. int totalRowNum = dtoList.size();
  9. int rowNum = 0;
  10. final int MAX_ROW_NUM = 1000;
  11. int fileNum = 0;
  12. String csvData = "";
  13. for (DTO dto : dtoList)  {
  14. rowNum++;
  15. // edit csv data
  16. ...
  17. if  (rowNum  % MAX_ROW_NUM == 0  ||
  18. rowNum == totalRowNum)  {
  19. // excel打开UTF乱码的对应
  20. byte[] csvDataBytes = csvData.getBytes();
  21. byte[] outputDataBytes = new byte[csvDataBytes.length + bom.length];
  22. System.arraycopy(bom, 0, outputDataBytes , 0, bom.length);
  23. System.arraycopy(csvDataBytes , 0, outputDataBytes , bom.length, csvDataBytes .length);
  24. DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(outputDataBytes ));
  25. // 添加到zip
  26. enc.add((++fileNum) + ".csv", dataInputStream, “123456”);
  27. if (rowNum < totalRowNum) {
  28. csvData = "";
  29. }
  30. }
  31. }
  32. out.flush();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. } finally {
  36. if (enc != null) {enc.close();}
  37. if (out != null) {out.close();}
  38. }

 

 

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

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

2. 压缩包里的文件名会出现乱码

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。