我想用 java.util.zip.ZipFile
读取一个 zip 文件与安卓 DocumentFile
插图:
使用 Storage Access Framework,我得到了 android 系统中一个文件的 uri,并用它创建了一个 Documentfile。文档文件是一个文件夹,其中包含一个 zip 文件“data.zip”
Data.zip 有超过 80 个条目,包括文本文件和媒体文件 (>= 8mb <= 20mb)。因此,zip 文件超过 932mb。
使用 filePAth,我可以使用下面的代码段直接读取条目:
zipFile = new ZipFile(zipPath);
ZipEntry zipEntry = zipFile.getEntry(name);
if (zipEntry != null) {
return writeByteArraysToFile(ByteStreams.toByteArray(zipFile.getInputStream(zipEntry)), ext);
}
这在不需要存储访问框架的设备上效果很好。
对于使用 SAF 的设备,我使用的是 DocumentFile,并且我正在阅读如下内容:
InputStream inputStream = context.getContentResolver().openInputStream(documentFile.getUri());
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream);
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
Log.e("field", entry.getName());
if (entry.getName().contains(name)) {
File file = PBUtils.writeByteArraysToFile(ByteStreams.toByteArray(zipInputStream), ext);
zipInputStream.closeEntry();
inputStream.close();
zipInputStream.close();
bufferedInputStream.close();
return file;
}
zipInputStream.closeEntry();
}
inputStream.close();
不是这个工作,但这里的问题是:
我需要有关如何使这更快的解决方案,并且需要知道是否有任何方法可以将 ZipFile 与 DocumentFile 一起使用,因此我至少可以执行以下操作:
zipFile = new ZipFile(documentFileUri);
ZipEntry zipEntry = zipFile.getEntry(name);
if (zipEntry != null) {
return writeByteArraysToFile(ByteStreams.toByteArray(zipFile.getInputStream(zipEntry)), ext);
}
最佳答案
这真的很糟糕——谷歌强制向我们提供不需要的 Scope Storage,但没有提供在需要时使用它的方法。一种方法:
// mDocFile is a DocumentFile..., you also need a context (activity, service, app...
String getDocReadableFilePath(DocumentFile mDocFile, Context context) {
if (mDocFile != null && mDocFile.isFile()) {
try {
ParcelFileDescriptor parcelFileDescriptor =
context.getContentResolver().openFileDescriptor(mUri, "r"); // gets FileNotFoundException here, if file we used to have was deleted
if (parcelFileDescriptor != null) {
int fd = parcelFileDescriptor.detachFd(); // if we want to close in native code
return "/proc/self/fd/" + fd;
}
}
catch (FileNotFoundException fne) {
return "";
}
}
}
// Now you may use:
String documentFilePath = getDocReadableFilePath(docFile, context);
ZipFile zf = new ZipFile(documentFilePath);
关于javascript - 使用 android DocumentFile 读取 ZipFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43026027/