问题
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,
回答1:
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();
}
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/5789430/creating-a-zip-file-with-some-files-on-sdcard