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);

}

 

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