在Android应用程序中解压SD卡中的压缩文件

17

我有一个被密码保护的zip压缩格式视频文件,保存在安卓模拟器的SD卡上。现在我想通过代码解压那个保存在SD卡上的视频文件。我该怎么做?需要帮助或者代码。 提前致谢。


http://www.google.com/search?q=android+unzip+file - Caner
1
这个问题之前已经被问过很多次了。它在Java库中而不是Android库中。请参见此处:https://dev59.com/gnA75IYBdhLWcg3wRW2c - HXCaine
请查看Android开发者网站上的ZipInputStream:http://developer.android.com/reference/java/util/zip/ZipFile.html - Seph
1
这里有Kotlin的解决方案 - https://dev59.com/gnA75IYBdhLWcg3wRW2c#50990872 它使用了一个文件扩展名。 - arsent
可能是 如何在Android中以编程方式解压文件? 的重复问题。 - arsent
请查看此方法:https://dev59.com/gnA75IYBdhLWcg3wRW2c#76032406 - Mori
4个回答

23
import android.util.Log; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 

/** 
 * 
 * @author jon 
 */ 
public class Decompress { 
  private String _zipFile; 
  private String _location; 

  public Decompress(String zipFile, String location) { 
    _zipFile = zipFile; 
    _location = location; 

    _dirChecker(""); 
  } 

  public void unzip() { 
    try  { 
      FileInputStream fin = new FileInputStream(_zipFile); 
      ZipInputStream zin = new ZipInputStream(fin); 
      ZipEntry ze = null; 
      while ((ze = zin.getNextEntry()) != null) { 
        Log.v("Decompress", "Unzipping " + ze.getName()); 

        if(ze.isDirectory()) { 
          _dirChecker(ze.getName()); 
        } else { 
          FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
          for (int c = zin.read(); c != -1; c = zin.read()) { 
            fout.write(c); 
          } 

          zin.closeEntry(); 
          fout.close(); 
        } 

      } 
      zin.close(); 
    } catch(Exception e) { 
      Log.e("Decompress", "unzip", e); 
    } 

  } 

  private void _dirChecker(String dir) { 
    File f = new File(_location + dir); 

    if(!f.isDirectory()) { 
      f.mkdirs(); 
    } 
  } 
} 
在您的情况下:
String zipFilename = Environment.getExternalStorageDirectory() + "/files.zip"; 
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipped/"; 

Decompress d = new Decompress(zipFilename, unzipLocation); 
d.unzip(); 

2
Divyesh,感谢您的回复。但我仍然感到困惑,因为我的压缩文件受到密码保护,那么我该如何匹配密码才能进入文件呢? - Suhail Larik
17
只是对你的答案进行补充,实际的读取和文件写入可以分块完成,这样可以比逐字节操作获得更高的性能:byte[] buffer = new byte[4096]; for (int c = zin.read(buffer); c != -1; c = zin.read(buffer)) { fout.write(buffer, 0, c); } - Rafael Nobre
1
@Nobre,你认为相同的代码适用于解压或打开扩展APK Expansion Files obb文件吗? - LOG_TAG
这是一个Xamarin.Android版本:https://gist.github.com/pauldendulk/18958a610adb50990d96 - pauldendulk

5

要解压受密码保护的文件,请使用此库:

http://www.lingala.net/zip4j/download.php

非常简单易操作。

ZipFile zipFile = new ZipFile(YourZipFile);
if(zipFile.isEncrypted())
    zipFile.setPassword(Password);
zipFile.extractAll(Destination);

2

其他的答案并不能解决在KitKat及以上版本中对SD卡(Environment.getExternalStorageDirectory() != SDCARD)的访问问题。但是你可以使用以下代码来实现API 21及以上版本的访问!如果需要更多帮助以获取zipDocumentFile,请阅读这篇文章

/**
 * @return true->successful
 */
public static Boolean unzip(Context context, DocumentFile zipDocumentFile) {

    try {

        InputStream inputStream = context.getContentResolver().openInputStream(zipDocumentFile.getUri());
        assert inputStream != null;
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE));

        ZipEntry ze;
        while ((ze = zipInputStream.getNextEntry()) != null) {
            if (ze.isDirectory()) {

                String[] paths = ze.getName().split("/");

                DocumentFile documentFile = null;
                for (String path : paths) {
                    if (documentFile == null) {
                        documentFile = zipDocumentFile.getParentFile().findFile(path);
                        if (documentFile == null)
                            documentFile = zipDocumentFile.getParentFile().createDirectory(path);
                    } else {
                        DocumentFile newDocumentFile = documentFile.findFile(path);
                        if (newDocumentFile == null) {
                            documentFile = documentFile.createDirectory(path);
                        } else {
                            documentFile = newDocumentFile;
                        }
                    }
                }

                if (documentFile == null || !documentFile.exists())
                    return false;

            } else {

                String[] paths = ze.getName().split("/");

                //Make Folders
                DocumentFile documentFile = null;
                for (int i = 0; i < paths.length - 1; i++) {
                    if (documentFile == null) {
                        documentFile = zipDocumentFile.getParentFile().findFile(paths[i]);
                        if (documentFile == null)
                            documentFile = zipDocumentFile.getParentFile().createDirectory(paths[i]);
                    } else {
                        DocumentFile newDocumentFile = documentFile.findFile(paths[i]);
                        if (newDocumentFile == null) {
                            documentFile = documentFile.createDirectory(paths[i]);
                        } else {
                            documentFile = newDocumentFile;
                        }
                    }
                }

                DocumentFile unzipDocumentFile;
                if (documentFile == null) {
                    unzipDocumentFile = zipDocumentFile.getParentFile().createFile(URLConnection.guessContentTypeFromName(ze.getName()), paths[paths.length - 1]);
                } else {
                    unzipDocumentFile = documentFile.createFile(URLConnection.guessContentTypeFromName(ze.getName()), paths[paths.length - 1]);

                }


                // unzip the file
                OutputStream outputStream = context.getContentResolver().openOutputStream(unzipDocumentFile.getUri());

                int read;
                byte[] data = new byte[BUFFER_SIZE];
                assert outputStream != null;
                while ((read = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1)
                    outputStream.write(data, 0, read);

                zipInputStream.closeEntry();

            }
        }

        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

2

这是Samir代码的稍微更简洁的版本,使用Apache的IOUtils.copy()来复制文件和finally块。如果您在归档中有大文件,则最好使用IOUtils.copyLarge()

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils {
    public static void unzip(InputStream is, File path) {
        checkDir(path);
        ZipInputStream zis = null;
        FileOutputStream fos = null;
        try {
            zis = new ZipInputStream(is);
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                File entryFile = new File(path, ze.getName());
                if (ze.isDirectory()) {
                    checkDir(entryFile);
                } else {
                    fos = new FileOutputStream(entryFile);
                    IOUtils.copy(zis, fos);
                    fos.close();
                    fos = null;
                }
                zis.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException ignore) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private static void checkDir(File path) {
        if (!path.exists()) {
            path.mkdirs();
        } else if (!path.isDirectory()) {
            throw new IllegalArgumentException("Path is not directory");
        }
    }
}

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