Home > File Compression > Nén file zip trong Java

Nén file zip trong Java

Java cung cấp thư viện java.util.zip để thực hiện việc nén dữ liệu thành định dạng zip. Toàn bộ quá trình khá là tường minh :

  1. Đọc file với FileInputStream
  2. Thêm tên file vào ZipEntry và đầu ra là ZipOutputStream

Ví dụ 1 : (Simple zip example ) 

Ví dụ này sẽ đọc file “test.txt” ( nằm trong thư mục của project ) và nén nó thành file “test.zip”

package quyetdv.java.javaio.filecompress;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CompressZipSimpleExample {
    public static void main(String[] args) {
        byte[] buffer = new byte[1024];
        try {
            FileOutputStream fos = new FileOutputStream("test.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry ze = new ZipEntry("test.txt");
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream("test.txt");
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
            zos.closeEntry();
            zos.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Ví dụ 2 : ( Avanced zip example – Recursively ) 

Ví dụ này sẽ đọc tất cả các file từ folder “C:\\testzip” và nén nó thành một file “C:\\MyFile.zip” . Nó sẽ thực hiện đệ quy zip thư mục.

package quyetdv.java.javaio.filecompress;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CompressZipAdvanceExample {
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String SOURCE_FOLDER = "C:\\testzip";
    public CompressZipAdvanceExample() {
        fileList = new ArrayList<String>();
    }
    public static void main(String[] args) {
        CompressZipAdvanceExample cz = new CompressZipAdvanceExample();
        cz.generateFileList(new File(SOURCE_FOLDER));
        cz.zipIt(OUTPUT_ZIP_FILE);
    }
    /**
     * 
     * @param zipFile : output ZIP file location
     */
    public void zipIt(String zipFile) {
        byte[] buffer = new byte[1024];
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            System.out.println("Output to Zip : " + zipFile);
            for (String file : this.fileList) {
                System.out.println("File Added : " + file);
                ZipEntry ze = new ZipEntry(file);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(SOURCE_FOLDER
                             + File.separator + file);
                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
            }
            zos.closeEntry();
            zos.close();
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
     }

    /**
    * Traverse a dicrectory and get all files,
    * and add the file into fileList
    * @param node : file or directory
    */
    public void generateFileList(File node)
    {
        // add file only
        if (node.isFile()) {
        fileList.add(generateZipEntry(node.getAbsolutePath().toString()));
        }

        if (node.isDirectory()) {
            String[] subNode = node.list();
            for (String fileName : subNode) {
                generateFileList(new File(node,fileName));
            }
        }
    }
   /**
    * Format the file path for zip
    * @param file : file path
    * @return : Formatted file path
    */
    private String generateZipEntry(String file)
    {
        return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}
Advertisements
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: