2010-06-03

利用 Java 將 Zip 格式解壓縮 (Use Java to decompress a ZIP file)

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;

public static void decompress(File source, File destination) throws IOException{
    if (!destination.exists() || destination.isDirectory()){
        destination.mkdirs();
        ZipInputStream zis = new ZipInputStream(new FileInputStream(source));
        byte[] buffer = new byte[1024];
        for (ZipEntry zip; (zip = zis.getNextEntry()) != null;){
            File file = new File(destination, zip.getName());
            if (zip.isDirectory()){
                file.mkdirs();
            } else {
                FileOutputStream fos = new FileOutputStream(file);
                for (int length; (length = zis.read(buffer)) > 0;){
                    fos.write(buffer, 0, length);
                }
                fos.close();
            }
            zis.closeEntry();
        }
        zis.close();
    }
}

沒有留言 :

張貼留言