如何从 ACTION_OPEN_DOCUMENT_TREE Intent 选择的文件夹中的 zip 文件中读取?

how to read from a zipfile in a folder which was selected by the ACTION_OPEN_DOCUMENT_TREE Intent?

如何从 ACTION_OPEN_DOCUMENT_TREE Intent 选择的文件夹中的 zip 文件中读取?

我的应用让用户通过 ACTION_OPEN_DOCUMENT_TREE Intent 选择文件夹。 在该文件夹中,我将有一个具有特定名称的 Zipfile。 目标是使用 java.util.zip.ZipFile.

读取 Zipfile

如何根据 onActivityResult 中提供的 URI(文件夹信息)使用此特定 Zipfilename 实例化 ZipFile?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri treeUri = data.getData();
    String sPath=treeUri.getPath();

    java.util.zip.ZipFile myzip=new java.util.zip.ZipFile("mypath"); <-- Constructor expects File or Path as String. Howto handle this with the Uri ?

How do I instantiate a ZipFile with this specific Zipfilename from the provided URI (Folderinfo) in onActivityResult ?

不能,因为没有文件,ZipFile 需要文件。你只能得到一个 InputStream,在 ContentResolver 上使用 openInputStream(),并且只有你得到一个 Uri 到你正在寻找的特定文件。

您的选项似乎是:

  • 使用ZipInputStream,可以包裹一个InputStream

  • 找一些接受 InputStream 作为输入的第三方库,并为您提供更好的 API

  • 将 ZIP 文件复制到应用程序的内部存储部分,然后使用 ZipFile

  • 读取其内容

我正在研究这个问题,最后采用了@CommonsWare 提到的策略作为第三个选项,即将文件复制到非 SD 卡位置并作为 ZipFile 加载。它运行良好,所以我将我的代码片段分享给大家。

 public static ZipFile loadCachedZipFromUri(Context context, Uri uri, String filename){
    File file = new File(context.getCacheDir(), filename);
    String fileName = context.getCacheDir().getAbsolutePath() + '/' + filename;
    ZipFile zip = null;

    if (file.exists()){
        Log.d(TAG, "file exists");
        try {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // N for Nougat
                zip = new ZipFile(fileName, Charset.forName("ISO-8859-1"));

            }else{
                zip = new ZipFile(fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zip;
    }

    DocumentFile dest = DocumentFile.fromFile(file);

    InputStream in = null;
    OutputStream out = null;

    Log.d(TAG, "Copy started");
    try {
        in = context.getContentResolver().openInputStream(uri);
        out = context.getContentResolver().openOutputStream(dest.getUri());
        byte[] buf = new byte[2048];
        int len = 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 = new ZipFile(fileName, Charset.forName("ISO-8859-1"));

        }else{
            zip = new ZipFile(fileName);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return zip;
}