zip File to ZipOutputStream - Android File Input Output

Android examples for File Input Output:Zip File

Description

zip File to ZipOutputStream

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    private static final int BUFF_SIZE = 1024 * 1024;

    public static void zipFile(File file, ZipOutputStream out) {
        String path = file.getName();

        byte[] buf = new byte[BUFF_SIZE];

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File aFile : files) {
                zipFile(aFile, out);//from  w  w  w  .  j  a  v  a 2  s  .  co  m
            }
        } else {
            try {
                BufferedInputStream in = new BufferedInputStream(
                        new FileInputStream(file), BUFF_SIZE);
                out.putNextEntry(new ZipEntry(path));
                int length;
                while ((length = in.read(buf)) != -1) {
                    out.write(buf, 0, length);
                }
                in.close();
                out.flush();
                out.closeEntry();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials