1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package com.sinosoft.am.zip;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.Map;
- import java.util.Properties;
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import org.apache.tools.zip.ZipEntry;
- import org.apache.tools.zip.ZipOutputStream;
- import com.sinosoft.common.upLoad.UpLoadFormServiceImpl;
- import com.sinosoft.common.util.FilePathUtil;
- public class DownZipFile {
- private static final Logger Log = Logger.getLogger(DownZipFile.class);
- //压缩包名称
- public static boolean filesToZip(String srcPath,String zipName, Map<String, String> fileNames) {
-
- boolean flag = false;
- if(fileNames.isEmpty()){
- return flag;
- }
- if (StringUtils.isEmpty(srcPath)) {
- return flag;
- }
- byte[] buffer = new byte[1024];
- try {
- srcPath = FilePathUtil.getUploadPath();
- Log.info("路径===:"+srcPath);
- //压缩包路径
- String strZipPath = srcPath + File.separator + zipName;
- //判断压缩包是否存在
- File zipFile = new File(strZipPath);
- if (zipFile.exists()) {
- // 删除已存在的目标文件
- zipFile.delete();
- }
- ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
- //需要被压缩的文件
- File[] files = new File[fileNames.size()];
- int index=0;
- //遍历所有要压缩的文件,并赋值给files
- for (Map.Entry<String, String> entry : fileNames.entrySet()) {
- entry.getKey();
- entry.getValue();
- files[index] = new File(srcPath + File.separator+entry.getKey());
- index++;
- }
- //开始压缩
- for (int i = 0; i < files.length; i++) {
- FileInputStream fis = new FileInputStream(files[i]);
- out.putNextEntry(new ZipEntry(fileNames.get(files[i].getName())));
- // 设置压缩文件内的字符编码,不然会变成乱码
- out.setEncoding("GBK");
- int len;
- // 读入需要下载的文件的内容,打包到zip文件
- while ((len = fis.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- }
- out.closeEntry();
- fis.close();
- }
- out.close();
- } catch (Exception e) {
- Log.error("文件压缩出错", e);
- return flag;
- }
- return true;
- }
- }
|