Java-工具类之ZIP压缩解压

概述

整理ZIP相关的工具类

这里写图片描述


实例

代码已托管到 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");
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小工匠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值