หน้าเว็บ

วันพฤหัสบดีที่ 7 มิถุนายน พ.ศ. 2555

สร้าง zip file ใน java (create zip file with java)


maven project
add dependencies (pom.xml)
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
        <type>jar</type>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>14.0.1</version>
        <type>jar</type>
    </dependency>

    <!-- log back -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.4</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.6</version>
    </dependency>
    <!-- log back -->
</dependencies>

logback สามารถดูได้จาก ใช้งาน Log Back

ZipFiles.java
package com.blogspot.na5cent.learning.zipfile;

import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author redcrow
 */
public class Zips {

    private static final Logger LOG = LoggerFactory.getLogger(Zips.class);
    //
    public static final String FILENAME_EXTENSION = "zip";
    private File fileOrFolder;
    private List<String> files;

    private Zips(File fileOrFolder) {
        this.fileOrFolder = fileOrFolder;
        files = new ArrayList<String>();
    }

    public static Zips fromFile(File fileOrFolder) throws FileNotFoundException {
        if (!fileOrFolder.exists()) {
            throw new FileNotFoundException(fileOrFolder.getName() + " not found.");
        }

        return new Zips(fileOrFolder);
    }

    public static Zips fromPath(String pathFileOrFolder) throws FileNotFoundException {
        return fromFile(new File(pathFileOrFolder));
    }

    private void copyFile(final InputStream inputStream, OutputStream outputStream) throws IOException {
        ByteStreams.copy(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return inputStream;
            }
        }, outputStream);
    }

    public void toZipFile(File targetZipFile) throws IOException {
        writeFile(targetZipFile);
    }

    public void toZipFile(String targetPathZipFile) throws IOException {
        toZipFile(new File(targetPathZipFile));
    }

    public void toZipOutputStream(OutputStream outputStream) throws IOException {
        zipToOutputStream(outputStream);
    }

    public void zip() throws IOException {
        getZipFile();
    }

    public FileInputStream getZipFileInputStream() throws IOException {
        return new FileInputStream(getZipFile());
    }
    
    private boolean isNotZipFile(File targetZipFile){
        return !FILENAME_EXTENSION.equalsIgnoreCase(FilenameUtils.getExtension(targetZipFile.getName()));
    }

    private void writeFile(File targetZipFile) throws IOException {
        if(isNotZipFile(targetZipFile)){
            throw new IllegalArgumentException(targetZipFile.getName() + " --> filename extension is not zip");
        }
        
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(targetZipFile);
            zipToOutputStream(outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    public File getZipFile() throws IOException {
        String zipName = FilenameUtils.getBaseName(fileOrFolder.getName()) + "." + FILENAME_EXTENSION;
        File targetZipFile = new File(fileOrFolder.getParent(), zipName);
        writeFile(targetZipFile);

        return targetZipFile;
    }

    private void zipToOutputStream(OutputStream outputStream) throws IOException {
        walkFolder(fileOrFolder);

        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(outputStream);

            for (String file : files) {
                putFileIntoZip(file, zipOutputStream);
            }
        } finally {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        }
    }

    private void putFileIntoZip(String file, ZipOutputStream zipOutputStream) throws IOException {
        LOG.debug("zip file --> {}", file);
        
        FileInputStream fileInputStream = null;
        try {
            ZipEntry entry = new ZipEntry(file);
            zipOutputStream.putNextEntry(entry);

            if (!file.endsWith(File.separator)) {
                File entryFile = new File(fileOrFolder.getParent(), file);
                fileInputStream = new FileInputStream(entryFile);
                copyFile(fileInputStream, zipOutputStream);
            }
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }

            zipOutputStream.closeEntry();
        }
    }
    
    private boolean canNotWalk(File file){
        File[] listFiles = file.listFiles();
        return listFiles == null || listFiles.length == 0;
    }

    private void walkFolder(File parent) {
        if (parent.isFile()) {
            files.add(getRealPath(parent));
        }

        if (canNotWalk(parent)) {
            if (parent.isDirectory()) {
                files.add(getRealPath(parent) + File.separator);
            }
            return;
        }

        for (File child : parent.listFiles()) {
            walkFolder(child);
        }
    }

    private String getRealPath(File file) {
        return file.getAbsolutePath().substring(fileOrFolder.getParent().length() + 1);
    }
}
ZipsTest.java
package com.blogspot.na5cent.learning.zipfile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 *
 * @author redcrow
 */
public class ZipsTest {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        File originalFile = new File("C:\\Users\\jittagornp\\Documents\\zipfile");
        File zipFile = new File("C:\\Users\\jittagornp\\Documents\\test.zip");
        
        Zips.fromFile(originalFile).toZipFile(zipFile);
    }
}


2 ความคิดเห็น:

  1. สุดยอด เด๋วเก็บไว้ลองทำดูค่ะ

    ตอบลบ
  2. ครับ ขอบคุณครับ
    ผมลองเขียนเองออกแบบเองดูก็สนุกดีน่ะครับ
    มันทำให้เรารู้จริงในสิ่งที่เรากำลังทำ

    ท้าทายดีครับกับการที่เขียนแล้วแชร์ให้คนอื่นเอา code เราไปใช้
    ไม่รู้ว่าเขาจะว่ายังไง ถ้าเป็นสมัยก่อนคงโดนด่า (อ่านไม่รู้เรื่อง) 555+

    ตอบลบ