使用 SDCard 上的一些文件创建一个 zip 文件 [英] Creating a zip file with some files on SDCard

查看:26
本文介绍了使用 SDCard 上的一些文件创建一个 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前我发布了一个问题,我意识到股票电子邮件应用程序无法在附件中发送多个文件:https://stackoverflow.com/questions/5773006/sending-email-with-multiple-attachement-fail-with-default-email-android-app-but

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.

用户必须在列表中选择一些 pdf 文件,然后使用股票应用程序通过电子邮件发送它们.由于多个附件失败,我将创建一个包含所有请求文件的 zip 文件并发送此唯一文件.

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.

那么,我可以用 SDCard 上的一些文件制作存档吗?

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

我目前发现的是:http://developer.android.com/reference/java/util/zip/ZipFile.html

公共 ZipFile(文件文件)

public ZipFile (File file)

由于:API 级别 1 构造了一个新的带有指定文件的 ZipFile.

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

但我不明白如何在多个文件中使用它.

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

非常感谢,

推荐答案

我修改了 静态链接答案中的代码 到一个静态类中,但这对我很有用:

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();
        }
    }
}

这篇关于使用 SDCard 上的一些文件创建一个 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆