Java 工具1:zip壓縮和下載

1.問題當數據個數比較多的時候需要壓縮導出處理,我們再次介紹一個z有關於zip的工具類

2代碼如下:

zipUtils

package com.trgis.gis.platform.hzdmdz.util;

import org.hsqldb.error.Error;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
    private static final int  BUFFER_SIZE = 2 * 1024;

        /**
         * 壓縮成ZIP 方法1
         * @param srcDir 壓縮文件夾路徑
         * @param out    壓縮文件輸出流
         * @param KeepDirStructure  是否保留原來的目錄結構,true:保留目錄結構;
         *                          false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
         * @throws RuntimeException 壓縮失敗會拋出運行時異常
         */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
        throws RuntimeException{


        long start = System.currentTimeMillis();

        ZipOutputStream zos = null ;

        try {

            zos = new ZipOutputStream(out);

            File sourceFile = new File(srcDir);

            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);

            long end = System.currentTimeMillis();

            System.out.println("壓縮完成,耗時:" + (end - start) +" ms");

        } catch (Exception e) {

            throw new RuntimeException("zip error from ZipUtils",e);

        }finally{

            if(zos != null){

                try {

                    zos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }


    }


        /**
         * 壓縮成ZIP 方法2
         * @param srcFiles 需要壓縮的文件列表
         * @param out           壓縮文件輸出流
         * @throws RuntimeException 壓縮失敗會拋出運行時異常
         */
    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

        /**
         * 遞歸壓縮方法
         * @param sourceFile 源文件
         * @param zos        zip輸出流
         * @param name       壓縮後的名稱
         * @param KeepDirStructure  是否保留原來的目錄結構,true:保留目錄結構;
         *                          false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
         * @throws Exception
         */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip輸出流中添加一個zip實體,構造器中name爲zip實體的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip輸出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();

        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原來的文件結構時,需要對空文件夾進行處理
                if(KeepDirStructure){
                    // 空文件夾的處理1
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 沒有文件,不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判斷是否需要保留原來的文件結構
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要帶上父文件夾的名字加一斜槓,
                        // 不然最後壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }
                }

            }
        }
    }




    /**
     *  根據路徑刪除指定的目錄或文件,無論存在與否
     *@param sPath  要刪除的目錄或文件
     *@return 刪除成功返回 true,否則返回 false。
     */
    public static boolean DeleteFolder(String sPath) {
        // 驗證字符串是否爲正確路徑名的正則表達式
        String matches = "[A-Za-z]:\\\\[^:?\"><*]*";
        // 通過 sPath.matches(matches) 方法的返回值判斷是否正確
        // sPath 爲路徑字符串
        Boolean  flag = false;
        File file = new File(sPath);
        // 判斷目錄或文件是否存在
        if (!file.exists()) {  // 不存在返回 false
            return flag;
        } else {

            // 判斷是否爲文件
            if (file.isFile()) {  // 爲文件時調用刪除文件方法
                return deleteFile(sPath);
            } else {  // 爲目錄時調用刪除目錄方法
                return deleteDirectory(sPath);
            }
        }
    }


    /**
     * 刪除單個文件
     * @param   sPath 被刪除文件的文件名
     * @return 單個文件刪除成功返回true,否則返回false
     */
    public static boolean deleteFile(String sPath) {
        Boolean  flag = false;
        File file = new File(sPath);
        // 路徑爲文件且不爲空則進行刪除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 實現刪除文件夾的方法,
     * @param sPath
     * @return
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符結尾,自動添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir對應的文件不存在,或者不是一個目錄,則退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        Boolean flag = true;
        //刪除文件夾下的所有文件(包括子目錄)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //刪除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //刪除子目錄
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //刪除當前目錄
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }
    public Long[] getLong(Long[] ids,int start,int end){
        int k = end - start;
        Long id[] = new Long[k];
        for(int i = start, j=0 ; i<end && j<k; i++,j++){
            id[j] = ids[i];
        }
        return id;
    }

    public static void main(String[] args) throws Exception {

        /* *//** 測試壓縮方法1  *//*
        FileOutputStream fos1 = new FileOutputStream(new File("d:/shp/zip/mytest01.zip"));

        ZipUtils.toZip("D:/shp/data", fos1,true);

        *//** 測試壓縮方法2  *//*

        List<File> fileList = new ArrayList<>();

        fileList.add(new File("D:/shp/dm_point.dbf"));
        fileList.add(new File("D:/shp/dm_point.fix"));
        fileList.add(new File("D:/shp/dm_point.shx"));
        fileList.add(new File("D:/shp/dm_point.shp"));
        fileList.add(new File("D:/shp/dm_point.prj"));*/

        //FileOutputStream fos2 = new FileOutputStream(new File("d:/shpzip/mytest02.zip"));

        // ZipUtils.toZip(fileList, fos2);

        String path = "D:\\shp\\data";
        //Boolean b =   DeleteFolder(path);

       // File dirFile = new File(path);
        //如果dir對應的文件不存在,或者不是一個目錄,則退出
      /*  if (!dirFile.exists() || !dirFile.isDirectory()) {
            dirFile.mkdirs();
        }*/

       /* if (!dirFile.exists() || !dirFile.isDirectory()) {
            File[] files = dirFile.listFiles();
            Error.printSystemOut(files.length+"");
        }*/
        Long ids[] = new Long[10005];
        for (int i = 0; i < 10005; i++) {
            ids[i] = Long.parseLong(i + "");
        }
        int j1=ids.length % 2000;
        int j = (int)Math.ceil(ids.length / 2000);
        if(j1>0){
           j+=1;
        }
        System.out.println(ids.length+"_"+j+j1);
        for (int i = 0; i < j; i++) {
            int start = i * 2000;
            int end = i * 2000 + 2000;
            if(i==j-1){
                end = i * 2000 + j1;
            }
            System.out.println(i+"_"+start+"_"+end);
            Long id[] = new Long[2000];
            for (int m = start, n = 0; m < end && n < 2000; m++, n++) {
                id[n] = ids[m];
            }
        }
    }

}

導出

String filePath ="src\\main\\resources\\shp\\alldata\\";
File file = new File(filePath);
// 判斷目錄或文件是否存在,是否爲文件
if (file.exists() || file.isDirectory() ||(file.listFiles().length>0)) {//存在導出

/** 1.設置response的header */
//	response.setContentType("application/zip");
	response.setContentType("application/octet-stream");
// 指明response的返回對象是文件流
	response.setHeader("Content-Disposition", "attachment; filename="+type+"_"+code+".zip");
	response.setCharacterEncoding("UTF-8");
	/** 2.調用工具類,下載zip壓縮包 */
	// 這裏我們不需要保留目錄結構
	ZipUtils.toZip(filePath, response.getOutputStream(),false);
	//3.刪除文件
	//ZipUtils.DeleteFolder(filePath);
	logger.info("導出所有數據成功_"+code);

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章