ZipHelper.java 11.5 KB
Newer Older
yanzg's avatar
yanzg committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package com.yanzuoguang.util.helper;


import com.yanzuoguang.util.exception.CodeException;

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.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


yanzg's avatar
yanzg committed
23 24 25 26 27
/**
 * ZIP压缩处理工具类
 *
 * @author 颜佐光
 */
yanzg's avatar
yanzg committed
28 29 30 31 32 33 34 35 36 37 38 39
public class ZipHelper {

    /**
     * @param dirFile
     * @param zipFile
     * @throws IOException
     * @创建日期:2018年5月4日 下午3:07:55
     * @作者: meter
     * @描述:压缩指定目录下所有文件
     * @Title: zipDirectory
     */
    public static void zipDirectory(File dirFile, File zipFile) throws IOException {
yanzg's avatar
yanzg committed
40 41 42 43
        if (dirFile == null) {
            throw new CodeException("压缩时文件夹对象不能为空。");
        }
        if (!dirFile.isDirectory()) {
yanzg's avatar
yanzg committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
            throw new CodeException("[" + dirFile.getName() + "]不是一个文件夹,或者不存在。");
        }
        if (zipFile == null) {
            zipFile = new File(dirFile.getAbsolutePath() + ".zip");
        }
        String dirName = dirFile.getName() + File.separator;
        // 创建zip输出流
        ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName("UTF-8"));
        try {
            // 创建缓冲输出流
            BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
            try {
                dealDirFile(dirFile, dirName, bufferOutStream, zipOutStream);
            } finally {
                //最后关闭输出流
                bufferOutStream.close();
            }
        } finally {
            zipOutStream.close();
        }
    }

    /**
     * 讲文件添加到新目录,并且添加一个新文件
     *
     * @param zipTo       目标ZIP
     * @param zipFrom     来源ZIP
     * @param sourcePath  下载路径
     * @param sourceFiles 需要添加的文件
     * @throws Exception
     */
    public static void zipTo(File zipTo, File zipFrom, String sourcePath, File... sourceFiles) throws IOException {
        // 创建zip输出流
        ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipTo), Charset.forName("UTF-8"));
        try {
            // 创建缓冲输出流
            BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
            try {
                copyZip(zipFrom, zipOutStream, bufferOutStream, getExpand(sourcePath, sourceFiles));

                for (File sourceFile : sourceFiles) {
                    zipFile(sourcePath, sourceFile, zipOutStream, bufferOutStream);
                }
            } finally {
                //最后关闭输出流
                bufferOutStream.close();
            }
        } finally {
            zipOutStream.close();
        }
    }

    /**
     * 讲文件添加到新目录,并且添加一个新文件
     *
     * @param zipTo       目标ZIP
     * @param sourcePath  下载路径
     * @param sourceFiles 需要添加的文件
     * @throws Exception
     */
    public static void zip(File zipTo, String sourcePath, File... sourceFiles) throws IOException {
        System.out.println("待压缩文件:" + zipTo.getAbsolutePath());
        boolean exints = zipTo.exists();
        // 添加到已经存在的压缩文件中
        File tempFile = new File(zipTo.getAbsolutePath() + ".tmp");

        // 创建zip输出流
        ZipOutputStream zipOutStream;
        if (exints) {
            // 创建临时压缩文件
            zipOutStream = new ZipOutputStream(new FileOutputStream(tempFile), Charset.forName("UTF-8"));
        } else {
            // 新创建压缩文件
            zipOutStream = new ZipOutputStream(new FileOutputStream(zipTo), Charset.forName("UTF-8"));
        }
        try {
            // 创建缓冲输出流
            BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
            try {
                if (exints) {
                    copyZip(zipTo, zipOutStream, bufferOutStream, getExpand(sourcePath, sourceFiles));
                }

                for (File sourceFile : sourceFiles) {
                    zipFile(sourcePath, sourceFile, zipOutStream, bufferOutStream);
                }
            } finally {
                //最后关闭输出流
                bufferOutStream.close();
            }
        } finally {
            zipOutStream.close();
        }

        // 假如存在,则删除临时文件,并更改临时文件名称
        if (tempFile.exists()) {
            boolean flag = zipTo.delete();
            if (flag) {
                tempFile.renameTo(zipTo);
            } else {
                throw new CodeException("删除文件失败");
            }
        }
    }

    /**
     * 获取需要排除的文件名和文件路径
     *
     * @param sourcePath   文件路径
     * @param sourceFiles  文件名
     * @return
     */
    private static List<String> getExpand(String sourcePath, File[] sourceFiles) {
        List<String> ret = new ArrayList<>();
        for (File sourceFile : sourceFiles) {
            ret.add(sourcePath + sourceFile.getName());
        }
        return ret;
    }

    /**
     * 讲压缩文件保存到另外一个压缩文件
     *
     * @param fromFile        来源文件
     * @param zipOutStream    目标文件
     * @param bufferOutStream 目标文件流
     * @param expandFiles     需要排除的文件
     * @throws IOException
     */
    private static void copyZip(File fromFile, ZipOutputStream zipOutStream, BufferedOutputStream bufferOutStream, List<String> expandFiles) throws IOException {
        ZipFile fromZipFile = new ZipFile(fromFile);

        Enumeration<? extends ZipEntry> fromEntries = fromZipFile.entries();
        while (fromEntries.hasMoreElements()) {
            ZipEntry fromEntry = fromEntries.nextElement();
            if (expandFiles.indexOf(fromEntry.getName()) > -1) {
                continue;
            }

            zipOutStream.putNextEntry(new ZipEntry(fromEntry.getName()));
            if (!fromEntry.isDirectory()) {
                write(fromZipFile.getInputStream(fromEntry), bufferOutStream);
            }
            zipOutStream.closeEntry();
        }
        fromZipFile.close();
    }

    /**
     * 执行文件压缩
     *
     * @param file            需要压缩的文件
     * @param zipOutStream    目标文件
     * @param bufferOutStream 目标文件流
     * @throws IOException
     */
    private static void zipFile(String sourcePath, File file, ZipOutputStream zipOutStream, BufferedOutputStream bufferOutStream) throws IOException {
        if (!file.exists()) {
            throw new CodeException("文件" + file.getAbsolutePath() + "不存在");
        }
        // 创建压缩文件实体
        ZipEntry entry = new ZipEntry(sourcePath + file.getName());
        // 添加实体
        zipOutStream.putNextEntry(entry);
        // 创建输入流
        BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(file));
        write(bufferInputStream, bufferOutStream);
        zipOutStream.closeEntry();
    }

    /**
     * @param inputStream
     * @param outStream
     * @throws IOException
     * @创建日期:2018年5月4日 下午2:09:37
     * @作者: meter
     * @描述:读写zip文件
     * @Title: write
     */
    private static void write(InputStream inputStream, OutputStream outStream) throws IOException {
        try {
            byte[] data = new byte[4096];
            int length = 0;
            while ((length = inputStream.read(data)) != -1) {
                outStream.write(data, 0, length);
            }
            outStream.flush();//刷新输出流
        } finally {
            inputStream.close();//关闭输入流
        }
    }

    /**
     * @param dirFile
     * @param parentDir
     * @param bufferOutStream
     * @param zipOutStream
     * @throws IOException
     * @创建日期:2018年5月4日 下午4:38:46
     * @作者: meter
     * @描述:处理目录文件
     * @Title: dealDirFile
     */
    private static void dealDirFile(File dirFile, String parentDir, BufferedOutputStream bufferOutStream, ZipOutputStream zipOutStream) throws IOException {
        File[] fileList = dirFile.listFiles();
yanzg's avatar
yanzg committed
249 250 251
        if (fileList == null) {
            return;
        }
yanzg's avatar
yanzg committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        for (File file : fileList) {
            if (file.isFile()) {
                // 创建压缩文件实体
                ZipEntry entry = new ZipEntry(parentDir + file.getName());
                // 添加实体
                zipOutStream.putNextEntry(entry);
                // 创建输入流
                BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(file));
                write(bufferInputStream, bufferOutStream);
            } else {
                dealDirFile(file, parentDir + file.getName() + File.separator, bufferOutStream, zipOutStream);
            }
        }
    }

    /**
     * @param dirPath
     * @param zipPath
     * @throws IOException
     * @创建日期:2018年5月4日 下午3:22:11
     * @作者: meter
     * @描述:重载zipDirectory
     * @Title: zipDirectory
     */
    public static void zipDirectory(String dirPath, String zipPath) throws IOException {
        if (zipPath == null || "".equals(zipPath)) {
            zipDirectory(new File(dirPath), null);
        } else {
            zipDirectory(new File(dirPath), new File(zipPath));
        }
    }
    //------------------------------------------------米特华丽的分割线----------------------------------------------------------------------------------------

    /**
     * @param zipFile
     * @param destDir
     * @throws IOException
     * @创建日期:2018年5月4日 下午4:00:41
     * @作者: meter
     * @描述:解压文件
     * @Title: unzip
     */
    public static void unzip(File zipFile, File destDir) throws IOException {
        ZipFile zipOutFile = new ZipFile(zipFile, Charset.forName("gbk"));
        Enumeration<? extends ZipEntry> entries = zipOutFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                File tempFile = new File(destDir.getAbsolutePath() + File.separator + entry.getName());
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
            } else {
                File tempFile = new File(destDir.getAbsolutePath() + File.separator + entry.getName());
                checkParentDir(tempFile);
                FileOutputStream fileOutStream = new FileOutputStream(tempFile);
                BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);
                write(zipOutFile.getInputStream(entry), bufferOutStream);
                bufferOutStream.close();
                fileOutStream.close();
            }
        }
        zipOutFile.close();//记得关闭zip文件
    }

    /**
     * @param file
     * @创建日期:2018年5月4日 下午4:37:41
     * @作者: meter
     * @描述:验证父目录是否存在,否则创建
     * @Title: checkParentDir
     */
    private static void checkParentDir(File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

}