SpringBoot Java 는 대상 파일 을 zip 파일 로 압축 합 니 다.

최근 에 정 리 된 코드 는 예전 에 QR 코드 그림 을 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 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;
	}

}

 
스 트림 출력 으로 포장 하 는 방법,간단 한 contrller 를 쓰 세 요.  테스트 해 봐.
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 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;
	}
}

여러 개의 파일 이 이전에 압축 된 것 은 바로 이 렇 기 때문에 구체 적 인 상황 에 따라 상응하는 수정 을 할 수 있다.
 

좋은 웹페이지 즐겨찾기