【问题标题】:Get Uri from file in either assets or res/raw从 assets 或 res/raw 中的文件获取 Uri
【发布时间】:2026-01-29 08:05:02
【问题描述】:

我试图让这个工作正常进行,并且我在网上查看了许多不同的资源(正如您从我制作的所有 cmets 中看到的那样)。我想访问位于 assets 或 res 中的 .pdf 文件;哪一种都没有关系,所以最简单的方法就可以了。

我有下面的方法,它将获取实际文件,并将调用另一个方法(在下面的第一个方法下),参数中包含 Uri。

非常感谢您的帮助,我将随时回答问题或添加更多内容。

private void showDocument(File file)
{
    //////////// ORIGINAL ////////////////////
    //showDocument(Uri.fromFile(file));
    //////////////////////////////////////////

    // try 1
    //File file = new File("file:///android_asset/RELATIVEPATH");

    // try 2
    //Resources resources = this.getResources();

    // try 4
    String PLACEHOLDER= "file:///android_asset/example.pdf";
    File f = new File(PLACEHOLDER);

    //File f = new File("android.resource://res/raw/slides1/example.pdf");

    //getResources().openRawResource(R.raw.example);

    // try 3
    //Resources resources = this.getResources();
    //showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));

    showDocument(Uri.fromFile(f));
}

protected abstract void showDocument(Uri uri);

【问题讨论】:

    标签: java android pdf uri android-resources


    【解决方案1】:

    来自link & Get URI of .mp3 file stored in res/raw folder in android

    sing资源id,格式为:

    "android.resource://[package]/[res id]"
    

    Uri 路径 = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);

    或者,使用资源子目录(类型)和资源名称(不带扩展名的文件名),格式为:

    “android.resource://[包]/[资源类型]/[资源名称]”

    Uri 路径 = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");

    【讨论】:

      【解决方案2】:

      如果您不知道资源的 ID,而只知道名称,则可以使用 Android Resouces objectgetIdentifier(...) 方法。您可以使用应用程序上下文的getResources() 检索后者。

      例如,如果您的资源存储在 /res/raw 文件夹中:

      String rawFileName = "example"  // your file name (e.g. "example.pdf") without the extension
      
      //Retrieve the resource ID:
      int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
      
      if ( resID == 0 ) {  // the resource file does NOT exist!!
          //Debug:
          Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");
      
          return;
      }
      
      //Read the resource:
      InputStream inputStream = context.getResources().openRawResource(resID);
      

      【讨论】:

        【解决方案3】:

        非常有用的帖子。

        这里有一个替代方法:尽可能使用 FileDescriptor 而不是 Uri。

        示例:(在我的情况下,它是一个原始音频文件)

        FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();
        
        this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);
        

        【讨论】: