尝试访问assets文件夹中的子文件夹

6

我的资产文件夹下有一棵子文件夹树...我试图访问该目录中的一个PDF文件...其URL如下:

url = QP/28/28/mth.pdf

完整目录如下:
ful directory = file:///data/data/com.example.testqstn/files/QP/28/28/mth.pdf

我使用以下代码访问了该路径

intent.setDataAndType(Uri.parse("file://" + getApplicationContext().getFilesDir()
       + "/"+url), "application/pdf");
startActivity(intent);
     finish();

我没有收到任何错误消息,但是PDF文件没有打开。当未使用子文件夹且PDF文件只存在于资产文件夹中时,则PDF文件会正确打开。 那么问题究竟是什么?此外,日志窗口不会显示任何错误信息。

1
另一个应用程序无法访问您的私有存储空间。因此,您需要将PDF存储在SD卡上。 - Pankaj Kumar
据我所知,本地代码无法访问资源。 - Arihant Godha
3个回答

4

您不需要传递文件路径,因为资产已经构建在apk中,所以您只需在此示例中使用此函数即可从资产读取文本文件。

      String[] files = assetManager.list("fonts/temp/temp1/HippaPrivarcyDocument");
      // Above line gives the list files in asset particular sub folder........
      InputStream input;
                try {
                    input = getAssets().open("fonts/temp/temp1/HippaPrivarcyDocument");
                    int size = input.available();
                    byte[] buffer = new byte[size];
                    input.read(buffer);
                    input.close();
                    // byte buffer into a string
                    text = new String(buffer);
                } catch (Exception e) {

                }

祝你一切顺利


如果我需要访问资产文件夹的子文件夹,该怎么办?你只提到了资产文件夹内部的内容,但我想知道子文件夹中的文件。 - Sethu

1

已解决

这其实非常简单... 要访问 assets 文件夹中的子文件夹,您需要使用以下方法...

首先通过文件名访问文件。

    File file = new File(getFilesDir(), fname);

当尝试打开文件时,请同时使用文件名和文件的URL

    in = assetManager.open(url+fname);

在意图中仅使用文件名,而不是整个路径。(我之前使用了整个路径)

    intent.setDataAndType(
        Uri.parse("file://" + getFilesDir() + "/"+fname),
        "application/pdf");

0

你必须使用三个///。试试这个:

intent.setDataAndType(Uri.parse("file:///android_asset/" + "relative_path");

你使用过android_asset文件夹吗?假设asset文件夹包含test1.txt(asset/test1.txt)..那么只需编写"file:///android_asset/" + "test1.txt" - Zohra Khan
请查看此GIT示例,其中显示了如何访问资产文件夹中的文件https://github.com/commonsguy/cw-advandroid/tree/master/WebView/GeoWeb1 - Zohra Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接