Archive

Archive for the ‘File Compression’ Category

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();
        dz.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
    }
    /**
    * 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()) {
            folder.mkdir();
        }
        // 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);
            }
            fos.close();
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
        System.out.println("Done");
     } catch (Exception e) {
        e.printStackTrace();
     }
  }
}
Advertisements
Categories: File Compression

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());
    }
}
Categories: File Compression