SpringBoot Java 将目标文件压缩成zip文件

最近整理出来的代码,以前好像做过将一堆二维码图片打包成zip的功能,突然看到代码,以前用Struts写的,换springboot框架后,我还是看看能不能整合一下以前那乱糟糟的代码

各种打包方式,文件夹下内容全部打包,文件打包,流打包,打包后以流的形式输出(下载zip)等等

直接上代码

package com.modou.tools.utils;

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

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.modou.tools.constant.ToolsExceptionConstant;
import com.modou.tools.entity.ZipStreamEntity;
import com.modou.tools.myexception.ToolsException;

/**
 * zip工具类
 * 
 * @author cdj
 * @date 2018年8月24日 上午10:03:15
 */
@Component
public class ZipUtils {

	/**
	 * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
	 * 
	 * @param sourceFilePath
	 *            :待压缩的文件路径
	 * @param zipFilePath
	 *            :压缩后存放路径
	 * @param fileName
	 *            :压缩后文件的名称
	 * @return
	 */
	public static boolean folderToZip(String sourceFilePath, String zipFilePath, String fileName) {
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;

		if (sourceFile.exists() == false) {
			System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");
			throw new ToolsException(ToolsExceptionConstant.NOTEXSITERROR_CODE,
					String.format(ToolsExceptionConstant.NOTEXSITERROR_MSG, sourceFilePath));
		} else {
			try {
				File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
				if (zipFile.exists()) {
					System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
					throw new ToolsException(ToolsExceptionConstant.EXSITERROR_CODE,
							String.format(ToolsExceptionConstant.EXSITERROR_MSG, zipFilePath, fileName + ".zip"));
				} else {
					File[] sourceFiles = sourceFile.listFiles();
					if (null == sourceFiles || sourceFiles.length < 1) {
						System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
						throw new ToolsException(ToolsExceptionConstant.EMPTYERROR_CODE,
								String.format(ToolsExceptionConstant.EMPTYERROR_MSG, sourceFilePath));
					} else {
						fos = new FileOutputStream(zipFile);
						zos = new ZipOutputStream(new BufferedOutputStream(fos));
						byte[] bufs = new byte[1024 * 10];
						for (int i = 0; i < sourceFiles.length; i++) {
							// 创建ZIP实体,并添加进压缩包
							ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
							zos.putNextEntry(zipEntry);
							// 读取待压缩的文件并写进压缩包里
							fis = new FileInputStream(sourceFiles[i]);
							bis = new BufferedInputStream(fis, 1024 * 10);
							int read = 0;
							while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
								zos.write(bufs, 0, read);
							}
						}
						flag = true;
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				// 关闭流
				try {
					if (null != bis)
						bis.close();
					if (null != zos)
						zos.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return flag;
	}

	/**
	 * 将sourceFilePath文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
	 * 
	 * @param sourceFilePath
	 *            :待压缩的文件路径
	 * @param zipFilePath
	 *            :压缩后存放路径
	 * @param fileName
	 *            :压缩后文件的名称
	 * @return
	 */
	public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		if (sourceFile.exists() == false) {
			System.out.println("待压缩的文件:" + sourceFilePath + "不存在.");
			throw new ToolsException(ToolsExceptionConstant.NOTEXSITERROR_CODE,
					String.format(ToolsExceptionConstant.NOTEXSITERROR_MSG, sourceFilePath));
		} else {
			try {
				File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
				if (zipFile.exists()) {
					System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
					throw new ToolsException(ToolsExceptionConstant.EXSITERROR_CODE,
							String.format(ToolsExceptionConstant.EXSITERROR_MSG, zipFilePath, fileName + ".zip"));
				} else {
					fos = new FileOutputStream(zipFile);
					zos = new ZipOutputStream(new BufferedOutputStream(fos));
					byte[] bufs = new byte[1024 * 10];
					// 创建ZIP实体,并添加进压缩包
					ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
					zos.putNextEntry(zipEntry);
					// 读取待压缩的文件并写进压缩包里
					fis = new FileInputStream(sourceFile);
					bis = new BufferedInputStream(fis, 1024 * 10);
					int read = 0;
					while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
						zos.write(bufs, 0, read);
					}
					flag = true;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				// 关闭流
				try {
					if (null != bis)
						bis.close();
					if (null != zos)
						zos.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return flag;
	}

	/**
	 * 将流的内容打包成fileName名称的zip文件,并存放到zipFilePath路径下
	 * 
	 * @param sourceFilePath
	 *            :待压缩的文件路径
	 * @param zipFilePath
	 *            :压缩后存放路径
	 * @param fileName
	 *            :压缩后文件的名称
	 * @return
	 */
	public static boolean streamToZip(InputStream fis, String streamfilename, String zipFilePath, String fileName) {
		boolean flag = false;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		try {
			File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
			if (zipFile.exists()) {
				System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
				throw new ToolsException(ToolsExceptionConstant.EXSITERROR_CODE,
						String.format(ToolsExceptionConstant.EXSITERROR_MSG, zipFilePath, fileName + ".zip"));
			} else {
				fos = new FileOutputStream(zipFile);
				zos = new ZipOutputStream(new BufferedOutputStream(fos));
				byte[] bufs = new byte[1024 * 10];
				// 创建ZIP实体,并添加进压缩包
				ZipEntry zipEntry = new ZipEntry(streamfilename);
				zos.putNextEntry(zipEntry);
				// 读取待压缩的文件并写进压缩包里
				bis = new BufferedInputStream(fis, 1024 * 10);
				int read = 0;
				while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
					zos.write(bufs, 0, read);
				}
				flag = true;
			}
			zos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			// 关闭流
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return flag;
	}

	/**
	 * 将流转成zip文件输出
	 * @param inputstream
	 *            文件流
	 * @param streamfilename
	 *            流文件的名称
	 * @param fileName zip包的名称
	 * @param response   
	 * @return
	 */
	public static boolean streamToZipStream(InputStream inputstream, String streamfilename, String fileName,
			HttpServletResponse response) {
		boolean flag = false;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			zos = new ZipOutputStream(out);
			byte[] bufs = new byte[1024 * 10];
			// 创建ZIP实体,并添加进压缩包
			ZipEntry zipEntry = new ZipEntry(streamfilename);
			zos.putNextEntry(zipEntry);
			// 读取待压缩的文件并写进压缩包里
			bis = new BufferedInputStream(inputstream, 1024 * 10);
			int read = 0;
			while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
				zos.write(bufs, 0, read);
			}
			flag = true;
			zos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			// 关闭流
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
				if (null != out)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return flag;
	}

	/**
	 * 将多个流转成zip文件输出
	 * @param listStream
	 *            文件流实体类对象
	 * @param fileName zip包的名称
	 * @param response   
	 * @return
	 */
	public static boolean listStreamToZipStream(List<ZipStreamEntity> listStream, String fileName, HttpServletResponse response) {
		boolean flag = false;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			zos = new ZipOutputStream(out);
			byte[] bufs = new byte[1024 * 10];
			for (ZipStreamEntity zipstream : listStream) {
				String streamfilename = StringUtils.isnull(zipstream.getName());
				// 创建ZIP实体,并添加进压缩包
				ZipEntry zipEntry = new ZipEntry(streamfilename);
				zos.putNextEntry(zipEntry);
				// 读取待压缩的文件并写进压缩包里
				bis = new BufferedInputStream(zipstream.getInputstream(), 1024 * 10);
				int read = 0;
				while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
					zos.write(bufs, 0, read);
				}
			}
			flag = true;
			zos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			// 关闭流
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
				if (null != out)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return flag;
	}

	public static void main(String[] args) throws FileNotFoundException {
		String sourceFilePath = "D:\\test\\ SYSUSER_1703_20180130.csv";

		File file = new File(sourceFilePath);
		InputStream fileInputStream = new FileInputStream(file);

		System.out.println(file.exists());
		String zipFilePath = "D:\\test";
		String fileName = "232wdsadwada";
		String streamfileName = "wwww.csv";
		// boolean flag = ZipUtils.fileToZip(sourceFilePath, zipFilePath, fileName);
		boolean flag = ZipUtils.streamToZip(fileInputStream, streamfileName, zipFilePath, fileName);
		if (flag) {
			System.out.println("文件打包成功!");
		} else {
			System.out.println("文件打包失败!");
		}
	}
}

ZipStreamEntity :

package com.modou.tools.entity;

import java.io.InputStream;

/**
 * zip相关  流文件实体类
 * @author cdj
 * @date 2018年8月24日 下午3:10:01
 */
public class ZipStreamEntity {

	public String name;
	public InputStream inputstream;

	public ZipStreamEntity() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ZipStreamEntity(String name, InputStream inputstream) {
		super();
		this.name = name;
		this.inputstream = inputstream;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public InputStream getInputstream() {
		return inputstream;
	}

	public void setInputstream(InputStream inputstream) {
		this.inputstream = inputstream;
	}

}

打包成流输出的方法,写个简单的controller  测试一下

package com.modou.tools.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.modou.tools.entity.JsonResult;
import com.modou.tools.entity.ZipStreamEntity;
import com.modou.tools.utils.ZipUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 工具集(乱七八糟的东西)
 * @author cdj
 * @date 2018年8月24日 上午9:13:05
 */
@RestController
@RequestMapping("/ToolsController")
@Api(value="工具集",tags={"工具集"})
public class ToolsController {
	
	@Autowired
	ZipUtils zipUtils;
	
	@ApiOperation("文件zip打包")
	@ApiImplicitParams({
	})
	@GetMapping("/ZipTools")
	public JsonResult zipTools(HttpServletResponse response,HttpServletRequest request) throws FileNotFoundException {
		String sourceFilePath = "D:\\test\\ SYSUSER_1703_20180130.csv";
		String sourceFilePath1 = "D:\\test\\6dfaaefb2ea84f75965bb26e245d824c.jpg";
		String fileName = request.getParameter("fileName");
		List<ZipStreamEntity> list = new ArrayList<>();
		fileName += ".zip";
		File file = new File(sourceFilePath);
		InputStream fileInputStream = new FileInputStream(file);
		File file2 = new File(sourceFilePath1);
		InputStream fileInputStream2 = new FileInputStream(file2);
		list.add(new ZipStreamEntity("xxxx.csv", fileInputStream));
		list.add(new ZipStreamEntity("xxss.jpg", fileInputStream2));
		
		System.out.println(file.exists());
		ZipUtils.listStreamToZipStream(list, fileName, response);
		return null;
	}
}

多个文件以前压缩就是这样了,根据具体情况还能做相应的修改。

猜你喜欢

转载自blog.csdn.net/atmknight/article/details/82021168