我想用java.util.zip.ZipFile和android DocumentFile来读取一个zip文件。
插图:
使用存储访问框架,我在android系统中获取文件的uri,并使用它创建一个Documentfile。文档文件是一个具有zip文件"data.zip“的文件夹。
Data.zip有80多个条目,包括文本文件和媒体文件( >= 8mb <= 20 8mb)。因此,zip文件超过932 So。
使用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);
}发布于 2019-11-11 16:56:48
这真是令人沮丧--谷歌( Google )正在向我们提供不必要的范围存储( 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);发布于 2020-05-11 15:51:22
对于android DocumentFile,您必须使用java.util.zip.ZipInputStream或java.util.zip.ZipOutputStream,而不是与android context.getContentResolver().openOutputStream()和context.getContentResolver().openInputStream()一起使用的java.util.zip.ZipFile。
https://stackoverflow.com/questions/43026027
复制相似问题