Java-工具类之ZIP压缩解压

简介: Java-工具类之ZIP压缩解压

概述


整理ZIP相关的工具类


20170909110629538.jpg

实例

代码已托管到 https://github.com/yangshangwei/commonUtils

zip压缩单个或者多个文件

package com.artisan.commonUtils.zip;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 
 * 
 * @ClassName: ZipUtility
 * 
 * @Description: 【Steps to Compress a File in Java 】
 * 
 *               Here are the steps to compress a file using Java code:
 * 
 *               1. Open a ZipOutputStream that wraps an OutputStream like
 *               FileOutputStream. The ZipOutputStream class implements an
 *               output stream filter for writing in the ZIP file format.
 * 
 *               2. Put a ZipEntry object by calling the putNextEntry(ZipEntry)
 *               method on the ZipOutputStream. The ZipEntry class represents an
 *               entry of a compressed file in the ZIP file.
 * 
 *               3. Read all bytes from the original file by using the
 *               Files.readAllBytes(Path) method.
 * 
 *               4. Write all bytes read to the output stream using the
 *               write(byte[] bytes, int offset, int length) method.
 * 
 *               5. Close the ZipEntry.
 * 
 *               6. Close the ZipOutputStream.
 * 
 *               You can also set the compression method and compression level
 *               using the following ZipOutputStream’s methods:
 * 
 *               A: setMethod(int method): there are 2 methods: DEFLATED (the
 *               default) which compresses the data; and STORED which doesn’t
 *               compress the data (archive only).
 * 
 *               B: setLevel(int level): sets the compression level ranging from
 *               0 to 9 (the default).
 * 
 * @author: Mr.Yang
 * 
 * @date: 2017年9月7日 下午8:24:15
 */
public class ZipUtility {
    /**
     * 
     * 
     * @Title: compressSingleFile
     * 
     * @Description: compress a file in ZIP format
     * 
     * @param filePath
     * 
     * @return: void
     */
    public static void compressSingleFile(String filePath, String outPut) {
        try {
            File file = new File(filePath);
            String zipFileName = file.getName().concat(".zip");
            System.out.println("zipFileName:" + zipFileName);
            // if you want change the menu of output ,just fix here
            // FileOutputStream fos = new FileOutputStream(zipFileName);
            FileOutputStream fos = new FileOutputStream(outPut + File.separator + zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry(file.getName()));
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            zos.write(bytes, 0, bytes.length);
            zos.closeEntry();
            zos.close();
        } catch (FileNotFoundException ex) {
            System.err.format("The file %s does not exist", filePath);
        } catch (IOException ex) {
            System.err.println("I/O error: " + ex);
        }
    }
    /**
     * 
     * 
     * @Title: compressMultipleFiles
     * 
     * @Description: compresses multiple files into a single ZIP file.
     * 
     *               The file paths are passed from the command line,
     * 
     *               and the ZIP file name is name of the first file followed by
     *               the .zip extension
     * 
     * @param filePaths
     * 
     * @return: void
     */
    public static void compressMultipleFiles(String... filePaths) {
        try {
            File firstFile = new File(filePaths[0]);
            String zipFileName = firstFile.getName().concat(".zip");
            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            for (String aFile : filePaths) {
                zos.putNextEntry(new ZipEntry(new File(aFile).getName()));
                byte[] bytes = Files.readAllBytes(Paths.get(aFile));
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
            }
            zos.close();
        } catch (FileNotFoundException ex) {
            System.err.println("A file does not exist: " + ex);
        } catch (IOException ex) {
            System.err.println("I/O error: " + ex);
        }
    }
    public static void main(String[] args) {
        ZipUtility.compressSingleFile("D:/JavaMaster.log", "H:");
        ZipUtility.compressMultipleFiles("D:/Temp.log", "D:/JavaMaster.log");
    }
}

unzip到指定目录

package com.artisan.commonUtils.zip;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
 * 
 * 
 * @ClassName: UnzipUtility
 * 
 * @Description: The java.util.zip package provides the following classes for
 *               extracting files and directories from a ZIP archive:
 * 
 *               A:----> ZipInputStream: this is the main class which can be
 *               used for reading zip file and extracting files and directories
 *               (entries) within the archive. Here are some important usages of
 *               this class:
 * 
 *               1.read a zip via its constructor
 *               ZipInputStream(FileInputStream)
 * 
 *               2.read entries of files and directories via method
 *               getNextEntry()
 * 
 *               3.read binary data of current entry via method read(byte)
 * 
 *               4.close current entry via method closeEntry()
 * 
 *               5.close the zip file via method close()
 * 
 * 
 * 
 *               B:----> ZipEntry: this class represents an entry in the zip
 *               file. Each file or directory is represented as a ZipEntry
 *               object. Its method getName() returns a String which represents
 *               path of the file/directory.
 * 
 *               The path is in the following form:
 *               folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext
 * 
 * @author: Mr.Yang
 * 
 * @date: 2017年9月7日 下午8:10:06
 * 
 * 
 * @comments The UnzipUtility class has a public method for extracting files and
 *           directories from a zip archive:
 * 
 *           unzip(String zipFilePath, String destDirectory):
 * 
 *           extracts content of a zip file specified by zipFilePath to a
 *           directory specified by destDirectory.
 * 
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
    /**
     * Extracts a zip file specified by the zipFilePath to a directory specified
     * by destDirectory (will be created if does not exists)
     * 
     * @param zipFilePath
     * @param destDirectory
     * @throws IOException
     */
    public static void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
    /**
     * Extracts a zip entry (file entry)
     * 
     * @param zipIn
     * @param filePath
     * @throws IOException
     */
    public static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
    public static void main(String[] args) {
        String zipFilePath = "D:/test.zip";
        String destDirectory = "H:/";
        try {
            UnzipUtility.unzip(zipFilePath, destDirectory);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}


zip目录及子孙目录

package com.artisan.commonUtils.zip;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 
 * 
 * @ClassName: ZipWholeDirAndSubsDir
 * 
 * @Description: Using the walk file tree feature of Java NIO,
 * 
 *               you can write a program that compresses a whole directory
 *               (including sub files and sub directories) with ease
 * 
 * @author: Mr.Yang
 * 
 * @date: 2017年9月7日 下午8:36:18
 */
public class ZipWholeDirAndSubsDir extends SimpleFileVisitor<Path> {
    private static ZipOutputStream zos;
    private Path sourceDir;
    public ZipWholeDirAndSubsDir(Path sourceDir) {
        this.sourceDir = sourceDir;
    }
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
        try {
            Path targetFile = sourceDir.relativize(file);
            zos.putNextEntry(new ZipEntry(targetFile.toString()));
            byte[] bytes = Files.readAllBytes(file);
            zos.write(bytes, 0, bytes.length);
            zos.closeEntry();
        } catch (IOException ex) {
            System.err.println(ex);
        }
        return FileVisitResult.CONTINUE;
    }
    public static void main(String[] args) {
        String dirPath = "H:/Sessions";
        Path sourceDir = Paths.get(dirPath);
        try {
            String zipFileName = dirPath.concat(".zip");
            zos = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new ZipWholeDirAndSubsDir(sourceDir));
            zos.close();
        } catch (IOException ex) {
            System.err.println("I/O Error: " + ex);
        }
    }
}

不解压读取zip中的文件列表

package com.artisan.commonUtils.zip;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
 * 
 * 
 * @ClassName: ReadContentFromZipFile
 * 
 * @Description: Reading content of a ZIP file means that you list all entries
 *               contained in the file without extracting them.
 * 
 * 
 *               In the java.util.zip package, the ZipFile class can be used to
 *               open and read a ZIP file like this:
 * 
 *               ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<?
 *               extends ZipEntry> entries = zipFile.entries();
 * 
 * 
 *               Each entry is of type ZipEntry which provides the following
 *               methods for reading information of an individual entry (to name
 *               a few):
 * 
 *               getName(): returns the name of the entry in form of a relative
 *               path
 * 
 *               getComment(): returns comment of the entry getCompressedSize():
 *               returns the compressed size of the entry in bytes.
 * 
 *               getSize(): returns the normal size (uncompressed) of the entry
 *               in bytes.
 * 
 *               isDirectory(): tells whether the entry is a directory or not.
 * 
 * @author: Mr.Yang
 * 
 * @date: 2017年9月7日 下午8:38:59
 */
public class ReadContentFromZipFile {
    /**
     * 
     * 
     * @Title: readContentFromZipFile
     * 
     * @Description: TODO
     * 
     * @param zipFilePath
     * 
     * @return: void
     */
    public static void readContentFromZipFile(String zipFilePath) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String name = entry.getName();
                long compressedSize = entry.getCompressedSize();
                long normalSize = entry.getSize();
                String type = entry.isDirectory() ? "DIR" : "FILE";
                System.out.println(name);
                System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize);
            }
            zipFile.close();
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
    public static void main(String[] args) {
        ReadContentFromZipFile.readContentFromZipFile("D:\\test.zip");
    }
}


相关文章
|
1月前
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
58 4
|
2月前
|
算法 搜索推荐 Java
java 后端 使用 Graphics2D 制作海报,画echarts图,带工具类,各种细节:如头像切割成圆形,文字换行算法(完美实验success),解决画上文字、图片后不清晰问题
这篇文章介绍了如何使用Java后端技术,结合Graphics2D和Echarts等工具,生成包含个性化信息和图表的海报,并提供了详细的代码实现和GitHub项目链接。
156 0
java 后端 使用 Graphics2D 制作海报,画echarts图,带工具类,各种细节:如头像切割成圆形,文字换行算法(完美实验success),解决画上文字、图片后不清晰问题
|
2月前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
76 5
|
2月前
|
Java
Java 些许公共工具类
Java 些许公共工具类
17 1
|
3月前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
125 2
|
3月前
|
算法 Java
Java 压缩文件
在Java中压缩文件是一个常见的需求,通常可以通过使用Java自带的`java.util.zip`包来实现。这个包提供了`ZipOutputStream`类来创建ZIP格式的压缩文件。以下是一个简单的示例,展示了如何将多个文件压缩到一个ZIP文件中。 ### 示例:将多个文件压缩到一个ZIP文件中 ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFilesExample { public static vo
|
4月前
|
Java
Java应用结构规范问题之在UnitConvertUtils工具类将千米转换为米的问题如何解决
Java应用结构规范问题之在UnitConvertUtils工具类将千米转换为米的问题如何解决
|
4月前
|
存储 安全 算法
Java中防止压缩炸弹的技术分享
【8月更文挑战第17天】在软件开发和数据处理的日常工作中,我们经常会遇到各种压缩文件。然而,一种被称为“压缩炸弹”的恶意文件却给开发者带来了不小的困扰。压缩炸弹通过特殊设计的压缩算法,使得极小的文件在解压后能膨胀到异常巨大的体积,从而消耗大量系统资源甚至导致系统崩溃。本文将围绕“如何在Java中防止压缩炸弹”这一主题,分享一些实用的技术干货。
145 0
|
6月前
|
Java
排名前16的Java工具类
排名前16的Java工具类
43 0
|
Java
排名前16的Java工具类
排名前16的Java工具类
197 0