首页 > 解决方案 > 从 DocumentFile 中的 ZipInputStream 中从 ZipEntry 中获取 InputStream

问题描述

这是一个用 Java 完成的实验性 Android 项目。我需要的是从外部卡中读取 ZIP 文件(尽可能快),并在OSMDroid自定义切片提供程序InputStream每次需要时返回对应的条目。

当从主磁盘(或在其损坏的文件系统中调用的任何文件)提供 ZIP 时,我可以很容易地做到这一点,但是当尝试从外部卡读取时,较新版本的 Android 中唯一的选择是使用他们闪亮的SAF

当路径不是相对路径而是URI到外部卡时,我使用 aDocumentFile来检索 ZIP InputStream(显然,这是唯一的方法)。

DocumentFile file = DocumentFile.fromSingleUri(this, uri);
ContentResolver contentResolver = getContentResolver();
InputStream inStream = contentResolver.openInputStream(file.getUri());

问题 1:在这一点上,令人惊奇的是,DocumentFile由于它比好 ol 慢得多,使用已经对性能产生了影响File,能够将其inStream转换为ZipFile. 或者以某种方式直接ZipFileDocumentFile. 那可能吗?也许File从那得到DocumentFile一个ZipFile

我没有找到任何解决方案,所以我继续使用InputStream,我将其转换为ZipInputStream. 我的代码中的问题是我只能运行一次,而我需要的是每次需要来自 Zip 的文件流时都执行它。

public class MyZipFileArchive implements IArchiveFile {
    protected static ZipInputStream mZipInputStream;
}

public void init(InputStream inStream) {
    mZipInputStream = new ZipInputStream(inStream);
}

public InputStream getInputStream(ITileSource pTileSource, long pMapTileIndex) {
    final String path = pTileSource.getTileRelativeFilenameString(pMapTileIndex);
    ZipEntry entry = null;
    while ((entry = mZipInputStream.getNextEntry()) != null) {
        if (path.equals(entry.getName())) {
            return mZipInputStream;
        }
    }
    return null;
}

问题 2:第一次getInputStream调用它返回它找到的内容,但现在流在其末尾,第二次调用它,null返回。

所以,我需要一种方法来重置流,如果可能的话,每次调用函数时,或者使用另一种方法。我尝试在开始时将每个存储ZipEntry到 aList中,然后循环遍历它。它不起作用。另外,我没有找到转换ZipEntryInputStream需要返回的方法。

你会如何解决这个问题?基本上,我需要使用DocumentFile并且我需要从中获取一个ZipFile或一些快速的方法来找到它的条目。

标签: androidzipfileosmdroidstorage-access-framework

解决方案


推荐阅读