
使用java.util.zip包,实现文件的压缩与解压,并提供了下载方法
注意
- 无论是调用createNewFile()创建文件,还是在创建输出流时由输出流负责创建文件,都必须 保证父路径已经存在 ,否则文件无法创建
- 压缩或解压完成后及时关闭流
具体实现如下:
package com.mundo.monkey.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org. slf4j .Logger; import org.slf4j.LoggerFactory; public class file ZipUtil { private static final Logger logger = LoggerFactory.getLogger(FileZipUtil.class); /** * @Title: fileToZip * @Description: 文件压缩 * @param sourceFilePath文件源路径 * @param zipTargetPath压缩后存放路径 * @param fileName 压缩包 名 * @return * @date 2019年2月21日 下午9:38:54 * @author Mundo */public static String fileToZip(String sourceFilePath, String zipTargetPath, String fileName) { File sourceFile = new File(sourceFilePath); FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; ZipOutputStream zos = null; if (StringUtils.isBlank(zipTargetPath)) { throw new RuntimeException("压缩后文件的存放路径不存在!"); } // 父目录不存在(文件无法创建),生成父目录 if (!sourceFile.getParentFile(). exists ()) { sourceFile.getParentFile().mkdirs(); } try { File zipFile = new File(zipTargetPath + File.separator + fileName + ".zip");// zip、rar、war格式 if (zipFile.exists()) { zipFile.delete(); // 压缩包已存在,重新生成 logger.info(zipTargetPath + "目录下已经存在名字为:{}.zip打包文件.", fileName); } // zip文件路径不存在(文件无法创建),新建文件路径 if (!zipFile.getParentFile().exists()) { zipFile.getParentFile().mkdirs(); } File[] sourceFiles = sourceFile.listFiles(); if (null == sourceFiles || sourceFiles.length < 1) { logger.info("待压缩的文件目录:{}里面不存在文件,无需压缩", 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); } } } return zipFile.getAbsolutePath(); } catch (Exception e) { throw new RuntimeException(sourceFilePath + "压缩包生成失败!", e); } finally { try { // 压缩包生成后及时关闭流 if (null != bis) { bis. close (); } if (null != zos) { zos.close(); } if (null != fis) { fis.close(); } if (null != fos) { fos.close(); } } catch (IOException e) { throw new RuntimeException("压缩包生成失败!", e); } } } /** * @Title: unFileZip * @Description: zip文件解压 * @param sourcePath源文件 * @param targetPath目标文件夹 * @throws RuntimeException * @date 2019年2月21日 下午10:53:03 * @author Mundo */public static void unFileZip(String sourcePath, String targetPath) { File file = new File(sourcePath); // 判断源文件是否存在 if (!file.exists()) { logger.info("源文件路径{}不存在", sourcePath); } // 开始解压 ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); logger.info("当前文件{}", entry.getName()); // 如果是文件夹,就创建个文件夹 if (entry.isDirectory()) { String dirPath = targetPath + File.separator + entry.getName(); File dir = new File(dirPath); dir.mkdirs(); } else { // 如果是文件,就先创建一个文件,然后写出文件流 File targetFile = new File(targetPath + File.separator + entry.getName()); // 父文件夹不存在(文件就无法创建),那就创建文件夹 if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } targetFile.createNewFile(); // 将压缩文件内容写入到这个文件中 InputStream is = zipFile.getInputStream(entry); FileOutputStream fos = new FileOutputStream(targetFile); int len; byte[] buf = new byte[1024 * 10]; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } // 解压完成后,及时关流顺序,先打开的后关闭 if (null != fos) fos.close(); if (null != is) is.close(); } } logger.info("文件解压完成"); } catch (Exception e) { throw new RuntimeException("文件解压失败!", e); } finally { try { if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException("文件解压失败!", e); } } } /** * @Title: download * @Description: 文件下载 * @param filePath * @param response * @return * @date 2019年2月21日 下午11:12:23 * @author Mundo */public static Boolean download(String filePath, HttpServletResponse response) { File file = new File(filePath); if (file.exists()) { // 判断文件父目录是否存在 response.setContentType("application/force-download"); // 设置强制下载不打开 response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());// 设置文件名 byte[] buffer = new byte[1024]; FileInputStream fileInputStream = null; // 文件输入流 BufferedInputStream bufferedInputStream = null; OutputStream outputStream = null; // 输出流 try { outputStream = response.getOutputStream(); fileInputStream = new FileInputStream(file); bufferedInputStream = new BufferedInputStream(fileInputStream); int i = bufferedInputStream.read(buffer); while (i != -1) { outputStream.write(buffer); i = bufferedInputStream.read(buffer); } return true; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("文件下载失败!", e); } finally { try { // 关闭资源流 if (bufferedInputStream != null) bufferedInputStream.close(); if (fileInputStream != null) fileInputStream.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("流关闭失败", e); } } } return false; } public static void main(String[] args) { String fileToZip = fileToZip("C:\TestFile", "C:\ tmp ", UUID.randomUUID().toString()); logger.info("压缩后文件路径{}", fileToZip); unFileZip("C:\tmp\33b7478d-a564-4ff3-8032-cfdee99675a8.zip", "C:\tmp"); } }
每天进步一点点,你侬我侬不如码农,欢迎大家关注,文章定时更新,欢迎大家一起交流,一起进步~~~