如何在安卓设备中将文件压缩成zip文件夹?

21

我正在尝试通过电子邮件发送多个文件,我已经获得了将它们附加到电子邮件中的代码。

   Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                       sendIntent.setType("application/octet-stream");
  ArrayList<Uri> uris = new ArrayList<Uri>();
                       uris.add(0, Uri.parse("file://"+Environment.getExternalStorageDirectory()+ "/.file"));
    File f = getActivity().getDatabasePath(".db");
    Log.i(TAG,"DB path"+ f.getAbsolutePath());
    uris.add(1, Uri.fromFile(f));
    sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

但是现在,我需要将它们压缩成单个zip文件,然后将它们发送到电子邮件中。我看到了许多答案和想法,但我仍然无法得到一些清晰的想法。你们能帮助我解决这个问题吗?


1
请查看以下链接:http://www.jondev.net/articles/Zipping_Files_with_Android_(Programmatically)https://dev59.com/w2w15IYBdhLWcg3wVKJ1 - Atish Agrawal
1个回答

47

这些权限是为了将数据存储到您的设备存储中而需要的。
Mainfest.xml文件

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

请求写外置存储权限(更新于2018年10月04日)

 public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

Zip函数

public void zip(String[] _files, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            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.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

使用 Zip 函数

String[] s = new String[2];
 
// Type the path of the files in here
s[0] = inputPath + "/image.jpg";
s[1] = inputPath + "/textfile.txt"; // /sdcard/ZipDemo/textfile.txt
 
// first parameter is d files second parameter is zip file name
ZipManager zipManager = new ZipManager();
 
// calling the zip function
zipManager.zip(s, inputPath + inputFile);

解压函数

public void unzip(String _zipFile, String _targetLocation) {
 
        //create target location folder if not exist
        dirChecker(_targetLocatioan);
 
        try {
            FileInputStream fin = new FileInputStream(_zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
 
                //create dir if required while unzipping
                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
                    for (int c = zin.read(); c != -1; c = zin.read()) {
                        fout.write(c);
                    }
 
                    zin.closeEntry();
                    fout.close();
                }
 
            }
            zin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
}
private void dirChecker(String dir) {
    File f = new File(dir);
    if (!f.isDirectory()) {
            f.mkdirs();
    }
}

使用解压功能

ZipManager zipManager = new ZipManager();
zipManager.unzip(inputPath + inputFile, outputPath);

[来源:http://stacktips.com/tutorials/android/how-to-programmatically-zip-and-unzip-file-in-android]

本教程将介绍如何在Android应用程序中以编程方式创建ZIP文件和解压缩文件。
在Android开发中,我们可能需要压缩或解压缩文件,例如,在发送电子邮件附件之前,我们可以将多个文件打包到一个ZIP文件中。 在这种情况下,我们可以使用Java的ZipOutputStream类来创建ZIP文件,并使用ZipInputStream类来解压缩ZIP文件。
以下是创建ZIP文件的步骤:
1. 创建ZipOutputStream对象并将其连接到要写入的文件。 2. 使用putNextEntry()方法为每个文件创建新条目。 3. 使用write()方法将文件内容写入输出流。 4. 使用closeEntry()方法关闭当前条目。
以下是解压缩ZIP文件的步骤:
1. 创建ZipInputStream对象并将其连接到要读取的文件。 2. 使用getNextEntry()方法获取下一个条目。 3. 使用read()方法从输入流中读取数据。 4. 使用closeEntry()方法关闭当前条目。
以上就是在Android应用程序中以编程方式创建ZIP文件和解压缩文件的完整过程。

我在zip函数的inputfile类型处遇到了错误。 - Vicky
你的logcat中显示了什么错误? - B M
输入路径 = "/sdcard/ZipDemo"; 输入文件 = "/test.zip"; 输入路径是您设备上的压缩文件输出路径。 - B M
1
https://github.com/StackTipsLab/Advance-Android-Tutorials/blob/master/AndroidZip/src/com/zipp/ZipManager.java - live-love
Kotlin版本 - https://gist.github.com/prakashpro3/955d3cf82ca954037e92b497f0fb5d85 - undefined
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接