如何从资产文件中获取URI?

161

我一直在尝试获取资产文件的URI路径。

uri = Uri.fromFile(new File("//assets/mydemo.txt"));

当我检查文件是否存在时,我发现文件不存在

File f = new File(filepath);
if (f.exists() == true) {
    Log.e(TAG, "Valid :" + filepath);
} else {
    Log.e(TAG, "InValid :" + filepath);
}

有人可以告诉我如何提及存在于资产文件夹中的文件的绝对路径吗?

13个回答

0

是的,你不能从安卓手机或模拟器访问你的驱动器文件夹,因为你的电脑和安卓是两个不同的操作系统。我会选择安卓的res文件夹,因为它有很好的资源管理方法。除非你有非常好的理由把文件放在assets文件夹里,否则不要这样做。

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }

0
如果您不想使用资产文件夹并且希望获得一个URI而不将其存储在另一个目录中,您可以使用res/raw目录并创建一个帮助函数从resID获取URI:
internal fun Context.getResourceUri(@AnyRes resourceId: Int): Uri =
    Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(resourceId.toString())
        .build()

现在,如果您在res/raw目录下有一个名为mydemo.txt的文件,您可以通过调用上述辅助方法来轻松获取URI。

context.getResourceUri(R.raw.mydemo)

参考资料:https://dev59.com/Gmsz5IYBdhLWcg3wVGIy#57719958


-9

对我有用,尝试这段代码

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

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