如何使用存储卷(/StorageAccessFramework)解压缩文件? [英] How do you unzip a file with Storage Volume (/StorageAccessFramework)?

查看:108
本文介绍了如何使用存储卷(/StorageAccessFramework)解压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码(Android 7.0/牛轧糖)将zip文件解压缩到外部存储中(包括内部的多个文件夹级别):

I'm using this code (Android 7.0/Nougat) to unpack a zip file in external storage (including multiple folder levels inside):

try {
    ZipFile zip = new ZipFile(zippath);
    Enumeration enu = zip.entries();

    while(enu.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) enu.nextElement();
        BufferedInputStream bis = null;
        String fileName = null;

        try {
            fileName = zipEntry.getName();
            fileName = fileName.replace("\\",File.separator).replace("/",File.separator);
            int p = fileName.lastIndexOf(File.separator);

            if(p>=0) {
                File fd=new File(folderpath+File.separator+fileName.substring(0,p));
                fd.mkdirs();
            }

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(folderpath+File.separator+fileName));
            bis = new BufferedInputStream(zip.getInputStream(zipEntry));
            byte[] buffer = new byte[10000];
            int len = 0;

            while ((len = bis.read(buffer, 0, 10000)) > 0) {
                bos.write(buffer, 0, len);
            }

            bis.close();
            bos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }
    }
} catch (IOException e2) {
    e2.printStackTrace();
}

要获得对SD卡的写访问权限,我使用的是createAccessIntent(存储卷),它使用的是DocumentFile s而不是普通的File.

To get write access to the SD card I'm using createAccessIntent (Storage Volume) which uses DocumentFiles instead of the normal File.

我已经这样做以获得ZipInputStream:

InputStream inputStream = this.getContentResolver().openInputStream(myDocumentFileZip.getUri());
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream);
ZipEntry zipEntry;

...而且我猜你会继续这样:

...and I'm guessing that you continue like this:

while ((zipEntry = zipInputStream.getNextEntry()) != null) {

但是您从那里开始做什么?如何使用上面的代码将文件复制到SD卡上,并仍然保留文件夹结构,但是要使用存储卷(或Storage Access Framework)提供的内容呢?

But what do you do from there - how to you copy the files onto the SD card and still keep the folder structure like in the code above but using what Storage Volume (or Storage Access Framework) provides?

推荐答案

使用存储卷解压缩:

小心:如果您多次解压缩同一个.zip文件,它会创建副本,而第一篇文章中的原始代码(您不能将其用于SD卡)不会但会自动覆盖!/p>

Careful: This way it creates copies if you unzip the same .zip file multiple times, while my original code in the first post (which you can't use for an SD card) doesn't but instead overwrites automatically!

try {
    InputStream is = getContentResolver().openInputStream(myZip.getUri());
    BufferedInputStream bis = new BufferedInputStream(is);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry zipEntry;

    while ((zipEntry = zis.getNextEntry()) != null) {
        String fileName = null; 

        try {
            fileName = zipEntry.getName();        
            fileName = fileName.replace("\\",File.separator).replace("/",File.separator);
            int p=fileName.lastIndexOf(File.separator);        
            DocumentFile destFolder = myDestFolder; //DocumentFile of the destination folder
            String destName = fileName;

            if (p>=0) {
                String[] split = fileName.split(File.separator);

                //If the .zip file contains multiple folder levels, this is where you  
                //have to check and then create them, e.g. for 3 levels:
                if(split.length==1) {
                    destFolder = myFolder;
                    destName = filename;
                } else if(split.length==2) {
                    if(mySubFolder==null) {
                        mySubFolder = myFolder.createDirectory(split[0]);
                    }

                    destFolder = mySubFolder;
                    destName = split[1];
                } else if(split.length==3) {
                    if(mySubFolder==null) {
                        mySubFolder = myFolder.createDirectory(split[0]);
                    }
                    if(mySubSubFolder==null) {
                        mySubSubFolder = mySubFolder.createDirectory(split[1]);
                    }

                    destFolder = mySubSubFolder;
                    destName = split[2];
                }
            }

            DocumentFile df = null;

            //Now you have to tell it what file extensions ("MIME" type) you want to use, e.g.:
            if(destName.endsWith(".txt")) {
                df = destFolder.createFile("text/plain",destName.substring(0,destName.length()-4));
            } else if(destName.endsWith(".jpg")) {
                df = destFolder.createFile("image/jpeg",destName.substring(0,destName.length()-4));
            }

            OutputStream out = getContentResolver().openOutputStream(df.getUri());
            BufferedOutputStream bos = new BufferedOutputStream(out);
            long zipfilesize = zipEntry.getSize();

            byte[] buffer = new byte[10000];
            int len = 0;
            int totlen = 0;

            while (((len = zis.read(buffer, 0, 10000)) > 0) && (totlen < zipfilesize)) {
                bos.write(buffer, 0, len);
                totlen += len;
            }

            bos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }
    }

    is.close();
    bis.close();
    zis.close();
} catch (IOException e2) {
    e2.printStackTrace();
}

重要:java.util.zip没有设置sizecompressedSize(将返回"-1"),这就是为什么此代码将仅创建大小为的文件的原因. 0B使用库创建的zip文件-手动创建的zip文件(例如,使用WinRar)可以正常工作.要修复它,请替换

Important: java.util.zip doesn't set the size or compressedSize (will return "-1"), that's why this code will only create files with a size of 0B with zip files that were created by the library - zip files that were created by hand (e.g. with WinRar) work fine. To fix it, replace

while (((len = zis.read(buffer, 0, 10000)) > 0) && (totlen < zipfilesize)) {

使用

while (((len = zis.read(buffer, 0, 10000)) > 0)) {

之所以可以这样做,是因为:

It's possible to do this because:

对ZipInputStream.getNextEntry()的调用将InputStream置于条目的开头,因此提供ZipInputStream等同于提供ZipEntry的InputStream.

the call to ZipInputStream.getNextEntry() positions the InputStream at the start of the entry and therefore supplying the ZipInputStream is the equivalent of supplying a ZipEntry's InputStream.

来源: https://stackoverflow.com/a/3233600/2016165

此方法的缺点(与我的非StorageVolume版本相比)是:a)无法获得zip中的文件总数,b)也无法获取文件的(总)大小,这意味着您无法在解压缩..."对话框中设置进度条,除非您先对所有zip条目进行遍历以对其进行计数.

The disadvantages with this (in comparison to my non-StorageVolume version) are that you a) can't get the total amount of files in the zip and b) also can't get the (total) size of the files, which means that you can't set the progress bar in an "Unzipping..." dialog unless you iterate through all the zip entries first to count them.

这篇关于如何使用存储卷(/StorageAccessFramework)解压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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