Home > File Compression > Giải nén file zip trong Java

Giải nén file zip trong Java

Quá trình giải nén file zip trong Java gồm :

  1. Đọc file zip với “ZipInputStream”
  2. Nhận file vào “ZipEntry” và đầu ra là “FileOutputStream”

Ví dụ sau sẽ đọc file zip từ “C:\\MyFile.zip” và giải nén tất cả các file ra thư mục “C:\\output”

package quyetdv.java.javaio.filecompress;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class DecompressZipExample {
    List<String> fileList;
    private static final String INPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String OUTPUT_FOLDER = "C:\\output";
    public static void main(String[] args) {
        DecompressZipExample dz = new DecompressZipExample();
    * Unzip it
    * @param zipFile : input zip file
    * @param outputFolder : zip file output folder
    public void unZipIt(String zipFile, String outputFolder) {
        byte[] buffer = new byte[1024];
        try {
        // create output directory if it is not exists
        File folder = new File(OUTPUT_FOLDER);
        if (!folder.exists()) {
        // get the zip file content
        ZipInputStream zis = new ZipInputStream(
            new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator
                                + fileName);
            System.out.println("file unzip : " + newFile.getAbsolutePath());
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            ze = zis.getNextEntry();
     } catch (Exception e) {
Categories: File Compression
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: