06fb73f777486071b07485e051d1d07dc8e57efc.svn-base 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.sinosoft.am.zip;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.util.Map;
  6. import java.util.Properties;
  7. import org.apache.commons.lang.StringUtils;
  8. import org.apache.log4j.Logger;
  9. import org.apache.tools.zip.ZipEntry;
  10. import org.apache.tools.zip.ZipOutputStream;
  11. import com.sinosoft.common.upLoad.UpLoadFormServiceImpl;
  12. import com.sinosoft.common.util.FilePathUtil;
  13. public class DownZipFile {
  14. private static final Logger Log = Logger.getLogger(DownZipFile.class);
  15. //压缩包名称
  16. public static boolean filesToZip(String srcPath,String zipName, Map<String, String> fileNames) {
  17. boolean flag = false;
  18. if(fileNames.isEmpty()){
  19. return flag;
  20. }
  21. if (StringUtils.isEmpty(srcPath)) {
  22. return flag;
  23. }
  24. byte[] buffer = new byte[1024];
  25. try {
  26. srcPath = FilePathUtil.getUploadPath();
  27. Log.info("路径===:"+srcPath);
  28. //压缩包路径
  29. String strZipPath = srcPath + File.separator + zipName;
  30. //判断压缩包是否存在
  31. File zipFile = new File(strZipPath);
  32. if (zipFile.exists()) {
  33. // 删除已存在的目标文件
  34. zipFile.delete();
  35. }
  36. ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
  37. //需要被压缩的文件
  38. File[] files = new File[fileNames.size()];
  39. int index=0;
  40. //遍历所有要压缩的文件,并赋值给files
  41. for (Map.Entry<String, String> entry : fileNames.entrySet()) {
  42. entry.getKey();
  43. entry.getValue();
  44. files[index] = new File(srcPath + File.separator+entry.getKey());
  45. index++;
  46. }
  47. //开始压缩
  48. for (int i = 0; i < files.length; i++) {
  49. FileInputStream fis = new FileInputStream(files[i]);
  50. out.putNextEntry(new ZipEntry(fileNames.get(files[i].getName())));
  51. // 设置压缩文件内的字符编码,不然会变成乱码
  52. out.setEncoding("GBK");
  53. int len;
  54. // 读入需要下载的文件的内容,打包到zip文件
  55. while ((len = fis.read(buffer)) > 0) {
  56. out.write(buffer, 0, len);
  57. }
  58. out.closeEntry();
  59. fis.close();
  60. }
  61. out.close();
  62. } catch (Exception e) {
  63. Log.error("文件压缩出错", e);
  64. return flag;
  65. }
  66. return true;
  67. }
  68. }