Java 將文件打包為zip壓縮包下載


1、添加依賴

     <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.10.5</version>
        </dependency>

  

2、編寫工具類

  

package com.crtw.util;


import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;

/**
 * 生成壓縮文件 (zip,rar 格式)
 */
public class CompressUtil {

    /**
     * @param sourcePath   要壓縮的文件路徑
     * @param suffix 生成的格式后最(zip、rar)
     */
    public static void generateFile(String sourcePath, String suffix) throws Exception {

        File file = new File(sourcePath);
        // 壓縮文件的路徑不存在
        if (!file.exists()) {
            throw new Exception("路徑 " + sourcePath + " 不存在文件,無法進行壓縮...");
        }
        // 用於存放壓縮文件的文件夾
        String generateFile = file.getParent() + File.separator +"CompressFile";
        File compress = new File(generateFile);
        // 如果文件夾不存在,進行創建
        if( !compress.exists() ){
            compress.mkdirs();
        }
        // 目的壓縮文件
        String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + suffix;

        // 輸入流 表示從一個源讀取數據
        // 輸出流 表示向一個目標寫入數據

        // 輸出流
        FileOutputStream outputStream = new FileOutputStream(generateFileName);

        // 壓縮輸出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));

        generateFile(zipOutputStream,file,"");

        System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的壓縮文件生成位置:" + generateFileName);
        // 關閉 輸出流
        zipOutputStream.close();
    }

    /**
     * @param out  輸出流
     * @param file 目標文件
     * @param dir  文件夾
     * @throws Exception
     */
    private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {

        // 當前的是文件夾,則進行一步處理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();

            //將文件夾添加到下一級打包目錄
            out.putNextEntry(new ZipEntry(dir + "/"));

            dir = dir.length() == 0 ? "" : dir + "/";

            //循環將文件夾中的文件打包
            for (int i = 0; i < files.length; i++) {
                generateFile(out, files[i], dir + files[i].getName());
            }

        } else { // 當前是文件

            // 輸入流
            FileInputStream inputStream = new FileInputStream(file);
            // 標記要打包的條目
            out.putNextEntry(new ZipEntry(dir));
            // 進行寫操作
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            // 關閉輸入流
            inputStream.close();
        }

    }

    /**
     * 遞歸壓縮文件
     * @param output ZipOutputStream 對象流
     * @param file 壓縮的目標文件流
     * @param childPath 條目目錄
     */
    private static void zip(ZipOutputStream output,File file,String childPath){
        FileInputStream input = null;
        try {
            // 文件為目錄
            if (file.isDirectory()) {
                // 得到當前目錄里面的文件列表
                File list[] = file.listFiles();
                childPath = childPath + (childPath.length() == 0 ? "" : "/")
                        + file.getName();
                // 循環遞歸壓縮每個文件
                for (File f : list) {
                    zip(output, f, childPath);
                }
            } else {
                // 壓縮文件
                childPath = (childPath.length() == 0 ? "" : childPath + "/")
                        + file.getName();
                output.putNextEntry(new ZipEntry(childPath));
                input = new FileInputStream(file);
                int readLen = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
                    output.write(buffer, 0, readLen);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 關閉流
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

    /**
     * 壓縮文件(文件夾)
     * @param path 目標文件流
     * @param format zip 格式 | rar 格式
     * @throws Exception
     */
    public static String zipFile(File path,String format) throws Exception {
        String generatePath = "";
        if( path.isDirectory() ){
            generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator + path.getName() + "." + format: path.getParent() + path.getName() + "." + format;
        }else {
            generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator : path.getParent();
            generatePath += path.getName().substring(0,path.getName().lastIndexOf(".")) + "." + format;
        }
        // 輸出流
        FileOutputStream outputStream = new FileOutputStream( generatePath );
        // 壓縮輸出流
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
        zip(out, path,"");
        out.flush();
        out.close();

        return generatePath;
    }
    //測試
    public static void main(String[] args) {
    	String path = "F:\\Develop\\項目\\crawler";
        String format = "zip";
        try {
            System.out.println(zipFile(new File(path),format));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

}

  3、響應為下載

  

	//壓縮
			String zipFile = CompressUtil.zipFile(new File(rootPath), "zip");
			 response.setContentType("APPLICATION/OCTET-STREAM");  
		        response.setHeader("Content-Disposition","attachment; filename=company.zip");
		        try {
		    	//ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
		        	OutputStream out = response.getOutputStream();
		        	File ftp = ResourceUtils.getFile(zipFile);
		        	InputStream in = new FileInputStream(ftp);
		        
			        // 循環取出流中的數據
			        byte[] b = new byte[100];
			        int len;
			        while ((len = in.read(b)) !=-1) {
			        	  out.write(b, 0, len);
			          	}
			          in.close();
			          out.close();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM