java spring mvc 下载压缩包简洁代码,读取时候不分段读取。

java spring mvc 下载压缩包简洁代码,读取时候不分段读取。

package com.juanpi.service.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomFileUtil {
	private static Logger logger = LoggerFactory.getLogger(CustomFileUtil.class);

	public static List<File> getFiles(List<String> filePaths) {
		List<File> files = new ArrayList<File>();
		if (filePaths == null || filePaths.isEmpty()) {
			return null;
		}
		for (String t : filePaths) {
			if (t == null || ("").equals(t)) {
				continue;
			}
			File temp = new File(t);
			if (temp.exists()) {
				files.add(temp);
			}
		}
		if (files == null || files.isEmpty()) {
			return null;
		}
		return files;
	}

	/**
	 * @date 2016-10-18
	 * @author juanzi
	 * @param path
	 * @param fileName
	 *            创建文件
	 */
	public static void createFile(String path, String fileName) {
		File f = new File(path);
		File file = new File(f, fileName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				logger.error("zipFile createFile error:", e.getMessage(), e);
			}
		}

	}

	/**
	 * 压缩文件列表中的文件
	 * 
	 * @param files
	 * @param outputStream
	 * @throws IOException
	 */
	public static void zipFile(List<File> files, ZipOutputStream outputStream) {
		int size = files.size();
		// 压缩列表中的文件
		for (int i = 0; i < size; i++) {
			File file = (File) files.get(i);
			if (file.exists()) {
				zipFile(file, outputStream);
			}
		}
	}

	/**
	 * 将文件写入到zip文件中
	 * 
	 * @param inputFile
	 * @param outputstream
	 * @throws Exception
	 */
	public static void zipFile(File inputFile, ZipOutputStream outputstream) {
		FileInputStream inStream = null;
		BufferedInputStream bInStream = null;
		try {
			if (inputFile.isFile()) {
				inStream = new FileInputStream(inputFile);
				bInStream = new BufferedInputStream(inStream);
				ZipEntry entry = new ZipEntry(inputFile.getName());
				outputstream.putNextEntry(entry);
				byte[] buffer = new byte[2 * 1024 * 1024];
				int byteRead = 0;
				while ((byteRead = bInStream.read(buffer)) != -1) {
					outputstream.write(buffer, 0, byteRead);
				}
				outputstream.closeEntry(); // Closes the current ZIP entry
			}
		} catch (IOException e) {
			logger.error("zipFile IOException error:", e.getMessage(), e);
		} finally {
			try {
				if (bInStream != null) {
					bInStream.close();// 关闭
				}
				if (inStream != null) {
					inStream.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param file
	 * @param response
	 */
	public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
		BufferedInputStream fis = null;
		OutputStream toClient = null;
		try {
			// 以流的形式下载文件。
			fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			// 清空response
			response.reset();
			toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
			byte[] buffer = new byte[1024 * 1024];
			int byteRead = 0;
			while ((byteRead = fis.read(buffer)) != -1) {
				toClient.write(buffer, 0, byteRead);
			}
			toClient.flush();
			if (isDelete) {
				file.delete(); // 是否将生成的服务器端文件删除
			}
		} catch (IOException ex) {
			logger.error("compress file error" + ex.getMessage(), ex);
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (toClient != null) {
					toClient.close();
				}
			} catch (IOException e) {
				logger.error("compress file error" + e.getMessage(), e);
			}

		}
	}
}



restful接口如下

	/**
	 * 批量打包下载文件生成zip文件下载
	 * 
	 * @param session
	 */
	@CrossOrigin
	@RequestMapping(value = "/loadCompressedFolder", method = RequestMethod.GET)
	public String downloadFiles(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ZipOutputStream toClient = null;
		FileOutputStream outStream = null;
		try {
			List<String> filePaths = XXBussess.getAbsolutePaths();
			List<File> files = CustomFileUtil.getFiles(filePaths);
			if (files == null || files.isEmpty()) {
				return  "无可下载文件";
			}
			String fileName = UUID.randomUUID().toString() + ".zip"; // 在服务器端创建打包下载的临时文件
			String outFilePath = request.getSession().getServletContext().getRealPath("/");
			CustomFileUtil.createFile(outFilePath, fileName);
			File file = new File(outFilePath + fileName); // 文件输出流
			outStream = new FileOutputStream(file); // 压缩流
			toClient = new ZipOutputStream(outStream);
			CustomFileUtil.zipFile(files, toClient);
			toClient.close();
			outStream.close();
			CustomFileUtil.downloadFile(file, response, true);
			return null;
		} catch (Exception e) {
			logger.error("loadCompressedFolder error :", e.getMessage(), e);
			return  "下载失败";
		} finally {
			if (toClient != null) {
				toClient.close();
			}
			if (outStream != null) {
				outStream.close();
			}
		}
	}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值