Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a zip file with some files on SDCard

As I posted a question a few days ago, I realized thet the stock eMail app couldn't send multiple files in attachment: https://stackoverflow.com/questions/5773006/sending-email-with-multiple-attachement-fail-with-default-email-android-app-but

Unfortunately, I got no answer on it, so need to find a workaround.

The user has to select in a list some pdf and send them by email with stock app. As the multiple attachment fail, I will create a zip file with all the requested files and sent this unique file.

So, hoz can I make an archive with some files on SDCard?

What I currently found is this: http://developer.android.com/reference/java/util/zip/ZipFile.html

public ZipFile (File file)

Since: API Level 1 Constructs a new ZipFile with the specified file.

But I don't understand how to use this with multiple files.

Thank a lot,

like image 308
Waza_Be Avatar asked Apr 26 '11 11:04

Waza_Be


1 Answers

I modified the code from the static link answer into a static class, but this works great for me:

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 Zipper {
    private static final int BUFFER = 2048;

    public static void zip(String[] files, String zipFile) {
        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.finish();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 80
Quintin Balsdon Avatar answered Oct 28 '22 13:10

Quintin Balsdon