如何在Android中压缩文件

4

我有一个需要通过程序压缩文本文件的需求。

我已经在文件夹directory(context.getFilesDirectory())中创建了文本文件,
我想将这些文本文件压缩成一个zip文件并添加到Intent对象中。

请提供一段代码来说明如何在Android中压缩文件。

3个回答

8

如果你在SD卡上有一个文件夹,并且想要创建它的zip压缩包,那么只需将以下代码复制并粘贴到你的项目中,它会生成一个zip文件夹。这段代码会创建一个只包含文件而不含嵌套文件夹的文件夹zip压缩包。你可以根据需要进一步修改。

 String []s=new String[2]; //declare an array for storing the files i.e the path of your source files
  s[0]="/mnt/sdcard/Wallpaper/pic.jpg";    //Type the path of the files in here
  s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file

  zip((s,"/mnt/sdcard/MyZipFolder.zip");    //call the zip function


 public void zip(String[] files, String zipFile) 
 { 
    private String[] _files= files;
    private String _zipFile= 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.d("add:",_files[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(); 
} 

同时,使用以下代码在android-manifest.xml中添加权限

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

您有一个语法错误,两个无效的“private”关键字用法,以及BUFFER未定义。 - RenniePet
@RenniePet 但是为什么它在我这里运行呢,嗯? - Pir Fahim Shah
你能告诉我缓冲变量的理想值应该是多少吗? - user6649667
@14bce109 是的,它有大小限制,将BUFFER=1024放入代码中即可解决。如果还是不行,请私信我,我会帮助你的。 - Pir Fahim Shah
好的,但不要忘记检查文件路径是否为目录。 - MaxF
缓冲区 = 1024 * 1024 // 一兆字节。 - saksham

1

如果你想用密码压缩文件,可以查看这个库, 你需要在build.gradle中添加以下代码:

dependencies {
compile 'com.github.ghost1372:Mzip-Android:0.4.0'
}

这是压缩文件的代码:

Zip:

ZipArchive zipArchive = new ZipArchive();
zipArchive.zip(targetPath,destinationPath,password);

//这个库已经失效了,因为它在Github上不再可用。


不要使用那个库。它有漏洞。有时候,压缩文件的大小会随机变大。 - Azizi Musa

0

这是用于压缩文件的工作代码。您必须将要压缩的所有文件路径添加到arrayList中,并将其作为参数与所需zipfile的字符串名称一起发送到下面的函数。

 public String zipper(ArrayList<String> allFiles, String zipFileName) throws IOException
    {
        timeStampOfZipFile =new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
        App.mediaStorageDir.mkdirs();
        zippath = App.mediaStorageDir.getAbsolutePath() + "/" + zipFileName+ timeStampOfZipFile +  ".zip";
        try
        {
            if (new File(zippath).exists())
            {
                new File(zippath).delete();
            }
            //new File(zipFileName).delete(); // Delete if exists
            ZipFile zipFile = new ZipFile(zippath);
            ZipParameters zipParameters = new ZipParameters();
            zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            zipParameters.setPassword("Reset");

            if (allFiles.size() > 0)
            {
                for (String fileName : allFiles)
                {
                    File file = new File(fileName);
                    zipFile.addFile(file, zipParameters);
                }
            }


        }
        catch (ZipException e)
        {
            e.printStackTrace();
        }
        return zippath;
    }

这里是我的 App.class 中的静态最终字符串 mediaStorageApp.mediaStorageDir.mkdirs();
public static final File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
            "yourAppFoler");

创建目录,用于保存zip文件。函数的结果返回zip文件路径,可以将其附加到多部分实体以发送到服务器(如果需要)。

需要运行时权限API>=marshmellow

  <!-- == External Storage == -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

这段代码没有使用java.util.zip.ZipFile,因为它只能读取ZIP文件。相反,使用了net.lingala.zip4j.ZipFile - Salvador

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