Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping files and folders in android

So I created a class follwoing the examples found here. http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29 which is great, it works wonders, for files. When it comes to folders it does not work. I tried switching the strings to files and using isDirectory, but it was a no go. Here is the code:

import android.util.Log; 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {

    private static final int BUFFER = 2048;
    private String[] _files;
    private String _zipFile;

    public Compress(String[] files, String zipFile) {
        _files = files;
        _zipFile = zipFile;
    }

    public void zip() {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(_zipFile);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];
            for (int i = 0; i < _files.length; i++) {
                Log.v("Compress", "Adding: " + _files[i]);
                FileInputStream fi = new FileInputStream(_files[i]);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i]
                        .lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 388
Sam Zombi Avatar asked Nov 13 '22 13:11

Sam Zombi


1 Answers

Looks like it doesn't support adding directories with contents. So you should manually walk through directory structure and add all files inside directory and subdirectories.

like image 174
Nickolay Olshevsky Avatar answered Nov 16 '22 02:11

Nickolay Olshevsky