How To Read From A Zipfile In A Folder Which Was Selected By The Action_open_document_tree Intent?
Solution 1:
How do I instantiate a ZipFile with this specific Zipfilename from the provided URI (Folderinfo) in onActivityResult ?
You can't, as there is no file, and ZipFile
needs a file. You can only get an InputStream
, using openInputStream()
on a ContentResolver
, and that only if you get a Uri
to that specific file that you are looking for.
Your options appear to be:
Use
ZipInputStream
, which can wrap anInputStream
Find some third-party library that accepts an
InputStream
as input and gives you a better APICopy the ZIP flie to your app's portion of internal storage and read its contents using
ZipFile
Solution 2:
I was working on this problem and ended up going with a strategy @CommonsWare mentioned as the third option, which is copying a file to non-sdcard place and load as a ZipFile. It works well so I share my snippet for everybody.
publicstatic ZipFile loadCachedZipFromUri(Context context, Uri uri, String filename){
Filefile=newFile(context.getCacheDir(), filename);
StringfileName= context.getCacheDir().getAbsolutePath() + '/' + filename;
ZipFilezip=null;
if (file.exists()){
Log.d(TAG, "file exists");
try {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // N for Nougat
zip = newZipFile(fileName, Charset.forName("ISO-8859-1"));
}else{
zip = newZipFile(fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
return zip;
}
DocumentFiledest= DocumentFile.fromFile(file);
InputStreamin=null;
OutputStreamout=null;
Log.d(TAG, "Copy started");
try {
in = context.getContentResolver().openInputStream(uri);
out = context.getContentResolver().openOutputStream(dest.getUri());
byte[] buf = newbyte[2048];
intlen=0;
while((len = in.read(buf)) >= 0){
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Load copied file");
try {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // N for Nougat
zip = newZipFile(fileName, Charset.forName("ISO-8859-1"));
}else{
zip = newZipFile(fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
return zip;
}
Post a Comment for "How To Read From A Zipfile In A Folder Which Was Selected By The Action_open_document_tree Intent?"