zip source folder - Android File Input Output

Android examples for File Input Output:Zip File

Description

zip source folder

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    private static final int COMPRESSION_LEVEL = 8;
    private static final int BUFFER_SIZE = 1024 * 2;

    public static void zip(String sourcePath, String output)
            throws Exception {

        //  ?(sourcePath)    ?.
        File sourceFile = new File(sourcePath);

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        ZipOutputStream zos = null;

        try {/*from   w w  w.j  a v  a  2 s  .c o m*/
            fos = new FileOutputStream(output); // FileOutputStream
            bos = new BufferedOutputStream(fos); // BufferedStream
            zos = new ZipOutputStream(bos); // ZipOutputStream
            zos.setLevel(COMPRESSION_LEVEL); //   - ? ? 9, ? 8
            zipEntry(sourceFile, sourcePath, zos); // Zip  
            zos.finish(); // ZipOutputStream finish
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    private static void zipEntry(File sourceFile, String sourcePath,
            ZipOutputStream zos) throws Exception {
        // sourceFile   ?   ?  
        if (sourceFile.isDirectory()) {
            if (sourceFile.getName().equalsIgnoreCase(".metadata")) { // .metadata  return
                return;
            }
            File[] fileArray = sourceFile.listFiles(); // sourceFile    ?
            for (int i = 0; i < fileArray.length; i++) {
                zipEntry(fileArray[i], sourcePath, zos); // ? ?
            }
        } else { // sourcehFile   ? ?
            BufferedInputStream bis = null;
            try {
                String sFilePath = sourceFile.getPath();
                String zipEntryName = sFilePath.substring(
                        sourcePath.length() + 1, sFilePath.length());

                bis = new BufferedInputStream(new FileInputStream(
                        sourceFile));
                ZipEntry zentry = new ZipEntry(zipEntryName);
                zentry.setTime(sourceFile.lastModified());
                zos.putNextEntry(zentry);

                byte[] buffer = new byte[BUFFER_SIZE];
                int cnt = 0;
                while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    zos.write(buffer, 0, cnt);
                }
                zos.closeEntry();
            } finally {
                if (bis != null) {
                    bis.close();
                }
            }
        }
    }
}

Related Tutorials