Creating a zip file with some files on SDCard

后端 未结 2 2078
小蘑菇
小蘑菇 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: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();
            }
        }
    }
    

提交回复
热议问题