java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java文件分级目录打包下载zip

Java文件分级目录打包下载zip的实例代码

作者:无情的螺丝

这篇文章主要介绍了Java文件分级目录打包下载zip的实例代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Java文件分级目录打包下载zip

说一下具体实现的功能吧,要将页面的文件存放在对应的文件目录,打成压缩包下载。

由于第一次接触,也是找了一整天网上的方法,费尽脑汁,终于实现了。

打包下载zip的工具类

直接调用即可

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @Author: fd
 * @Date 2020/7/28 21:33
 * @Description:
 */
public class ZipUtiles {

	private static Logger logger = LoggerFactory.getLogger(ZipUtiles.class);
	// 目录标识判断符
	private static final String PATCH = "/";
	// 基目录
	private static final String BASE_DIR = "/b/";
	// 缓冲区大小
	private static final int BUFFER = 2048;
	// 字符集
	private static final String CHAR_SET = "UTF-8";

	public static void compress(File srcFile, ZipOutputStream zipOutputStream, String basePath) throws Exception {
		if (srcFile.isDirectory()) {
			compressDir(srcFile, zipOutputStream, basePath);
		} else {
			compressFile(srcFile, zipOutputStream, basePath);
		}
	}

	
	private static void compressDir(File dir, ZipOutputStream zipOutputStream, String basePath) throws Exception {
		try {
			// 获取文件列表
			File[] files = dir.listFiles();

			if (files.length < 1) {
				ZipEntry zipEntry = new ZipEntry(basePath + dir.getName() + PATCH);

				zipOutputStream.putNextEntry(zipEntry);
				zipOutputStream.closeEntry();
			}

			for (int i = 0,size = files.length; i < size; i++) {
				compress(files[i], zipOutputStream, basePath + dir.getName() + PATCH);
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage(), e);
		}
	}

	private static void compressFile(File file, ZipOutputStream zipOutputStream, String dir) throws Exception {
		try {
			// 压缩文件
			ZipEntry zipEntry = new ZipEntry(dir + file.getName());
			zipOutputStream.putNextEntry(zipEntry);

			// 读取文件
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

			int count = 0;
			byte data[] = new byte[BUFFER];
			while ((count = bis.read(data, 0, BUFFER)) != -1) {
				zipOutputStream.write(data, 0, count);
			}
			bis.close();
			zipOutputStream.closeEntry();
		} catch (Exception e) {
			throw new Exception(e.getMessage(),e);
		}
	}


	public static void main(String[] args) {
		try {
			ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File("D:/a/a.zip")));
			zipOutputStream.setEncoding(CHAR_SET);

			List<File> files = new ArrayList<File>();
			files.add(new File("D:\\a\\b\\1.jpg"));
			files.add(new File("D:\\a\\b\\2.jfif"));

			if (CollectionUtils.isEmpty(files) == false) {
				for (int i = 0,size = files.size(); i < size; i++) {
					compress(files.get(i), zipOutputStream, BASE_DIR);
				}
			}
			// 冲刷输出流
			zipOutputStream.flush();
			// 关闭输出流
			zipOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

页面下载方法的接口

业务逻辑可跟需求修改,这里主要是查询数据库得出文件名,根据自己需求构建分级文件名,存入集合,循环将对应的文件存放到文件夹里,调用工具类打成压缩包下载。

	/**
	 * 打包下载
	 */
	@RequestMapping(value = "/packdownload", method = RequestMethod.GET)
	public void packdownload(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		PrintWriter outWriter = null;
		try {
			//查询条件
			String loanId = request.getParameter("loanId")==null?"":request.getParameter("loanId").trim();
			String contNo = request.getParameter("contNoStr")==null?"":request.getParameter("contNoStr").trim();
			
			Criteria cri = new Criteria();
			cri.clear();
			//业务需求 查询文件的条件
			if(StringUtils.isNotBlank(loanId) && !loanId.equals("")){
				cri.put("loanId",loanId);
			}
			//查询出来的文件集合
			List<TFileConfig> tFileConfigList = fileConfigService.selectByCondition(cri);
			if(tFileConfigList != null && tFileConfigList.size() > 0){
				String zipName = contNo + "信贷档案信息.zip";
				response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
				response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName, "UTF-8"));
				ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				zipOutputStream.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法

				try {
					//以下代码为 根据自己所需条件查询数据库得出文件夹名 构建二级文件夹名
					List<File> files = new ArrayList<File>();
					List<String> totalFolderList = new ArrayList<String>();
					TFileConfig fileConfig = null;
					for (int i = 0;i < tFileConfigList.size(); i++){
						fileConfig = tFileConfigList.get(i);
						cri.clear();
						cri.put("loanConfigId",fileConfig.getLoanConfigId());
						List<TLoanConfig> loanConfigList = tLoanConfigService.selectByCondition(cri);		//根据loanConfigId 查找对应 的 配置类名
						if(loanConfigList != null && loanConfigList.size() > 0){
							String folderName = loanConfigList.get(0).getLoanConfigName();	//子类文件名
							cri.clear();
							cri.put("superIds",loanConfigList.get(0).getSuperId());
							List<TLoanConfig> superConfigList = tLoanConfigService.selectByCondition(cri);
							if(superConfigList != null && superConfigList.size() > 0){
								TLoanConfig config = superConfigList.get(0);
								String superConfigName = config.getLoanConfigName();	//父类文件夹名
								totalFolderList.add(superConfigName + "\\" + folderName + "\\");	//构建二级文件夹名
							}	
							files.add(new File(fileConfig.getRealPath()));
						}
					}
					if (CollectionUtils.isEmpty(files) == false) {
						for (int i = 0,size = totalFolderList.size(); i < size; i++) {
							//调用工具类方法
							ZipUtiles.compress(files.get(i), zipOutputStream, totalFolderList.get(i));
					}
					response.flushBuffer();
					// 冲刷输出流
					zipOutputStream.flush();
					zipOutputStream.finish();
					// 关闭输出流
					zipOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				outWriter = response.getWriter();
				outWriter.println("<script>alert('该日期暂无文件')';</script>");
				return;
			}
		} catch (Exception e) {
			try {
				outWriter = response.getWriter();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			logger.error("ImportfileController.java-packdownload-Exception: ", e);
			outWriter.println("<script>alert('下载异常')';</script>");
			return;
		}
	}

页面下载调用后台接口

function subFrm(){
      var options = {
        dataType: 'json',
        iframe:	false,
        resetForm: true,
        success: function(data) {
          debugger;
          if(data.code == 1){
              layer.alert('校验成功', {icon: 1},function(index){
                var url = pcs.common.path + '/admin/sysfiles/packdownload?loanId=' + $("#loanId").val() +  "&contNoStr=" + $("#contNoStr").val();
                window.location.href = url;
                  //关闭弹窗
                  setTimeout(function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                  }, 500)

              });
          }else{
              layer.alert(data.msg, {icon: 2});
          }
        },
        error:function(){
            layer.alert('页面已过期,请刷新', {icon: 2},function(){
                window.location.href = pcs.common.path + '/admin/user/confirmPwd';
            });
        }
      };
      $.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
      $('#frm').ajaxSubmit(options);
    }

这是页面文件的展示页

点击下载即可打包文件,下载压缩包。

下载成功的展示

解压后的文件

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文