Creating a zip file with some files on SDCard

后端 未结 2 2071
小蘑菇
小蘑菇 2021-02-06 01:56

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

相关标签:
2条回答
  • 2021-02-06 02:36

    ZipFile is a shortcut for the one file case. If you want to do multiple files, you need to work with a ZipOutputStream - just one click away from the javadoc page you quoted.

    And that javadoc also has an example on how to zip up multiple files.

    0 讨论(0)
  • 2021-02-06 02:55

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题