简单的文件夹压缩ZIP文件

一.压缩文件夹,生产zip压缩文件

/**
 * 生成zip文件
 * @param folderPath 文件夹路径
 * @param targetFile 文件夹名
 */
public  boolean  createZip(String folderPath,String targetFile){
		//要压缩的文件夹路径
		String folderToCompress = folderPath+targetFile;
		//生成的zip文件路径
		String zipFileName = folderToCompress+".zip";
		//文件名称
		String folderName = targetFile;
		try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName))) {
			// 压缩文件夹
			ZipPoi.compressFolder(folderToCompress, folderName, zipOutputStream);
			System.out.println("Folder compressed successfully!");
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		}
		return true;
	}

所用到的公共类

/**
 *	公共类
 * @author guanc
 * @ClassName ZipPoi
 * @date 2023年08月27日
 * @version: 1.0
 */
public class ZipPoi {
    /**
     * 压缩文件夹
     * @param sourceFolder 要压缩的文件夹路径  如要压缩windos文件夹 则路径为  E:\opt\dag\client\windows
     * @param folderName  文件名称 windows.zip
     * @param zipOutputStream
     * @throws IOException
     */
    public static void compressFolder(String sourceFolder, String folderName, ZipOutputStream zipOutputStream) throws IOException {
        File folder = new File(sourceFolder);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 压缩子文件夹
                    compressFolder(file.getAbsolutePath(), folderName + "/" + file.getName(), zipOutputStream);
                } else {
                    // 压缩文件
                    addToZipFile(folderName + "/" + file.getName(), file.getAbsolutePath(), zipOutputStream);
                }
            }
        }
    }
    //添加压缩文件
    public static void addToZipFile(String fileName, String fileAbsolutePath, ZipOutputStream zipOutputStream) throws IOException {
        // 创建ZipEntry对象并设置文件名
        ZipEntry entry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(entry);

        // 读取文件内容并写入Zip文件
        try (FileInputStream fileInputStream = new FileInputStream(fileAbsolutePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                zipOutputStream.write(buffer, 0, bytesRead);
            }
        }

        // 完成当前文件的压缩
        zipOutputStream.closeEntry();
    }
}

2.下载zip文件

/**
	 * 下载目标文件,其中目标文件是zip文件
	 *
	 * @param targetFile 目前文件
	 * @param response
	 * @return
	 */
	@GetMapping("/downloadZip")
	public void downloadZip(@RequestParam String targetFile, HttpServletResponse response) {
		//文件路径 C:/opt/dag/client/
		String folderPath = "C:/opt/dag/client/";
		String filePath = folderPath + targetFile+".zip";
		try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + targetFile +".zip"+ "\"");
			response.setHeader("Access-Control-Allow-Origin", "*");
			File downloadFile = new File(filePath);
			if (downloadFile.exists()&& !downloadFile.isDirectory()) {
				FileInputStream myStream = new FileInputStream(filePath);
				IOUtils.copy(myStream, response.getOutputStream());
			}else {
				boolean createZip = createZip(folderPath, targetFile);
				if (createZip){
					downloadZip(targetFile,response);
				}
			}
			response.flushBuffer();
			log.info("获取文件成功!");
		} catch (IOException e) {
			log.error(e.getMessage());
			boolean createZip = createZip(folderPath, targetFile);
			if (createZip){
				downloadZip(targetFile,response);
			}
		}
	}

完结!撒花!

你可能感兴趣的:(工具,java)