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

发布于 2024-10-14 19:03:04 字数 343 浏览 7 评论 0原文

我一直在尝试获取资产文件的 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);
}

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

I have been trying to get the URI path for an asset file.

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

When I check if the file exists I see that file doesn't exist

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

Can some one tell me how I can mention the absolute path for a file existing in the asset folder

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

风透绣罗衣 2024-10-21 19:03:04

不存在“资产文件夹中存在的文件的绝对路径”。项目的 assets/ 文件夹的内容打包在 APK 文件中。使用 AssetManager 对象来获取资产上的 InputStream

对于 WebView,您可以像使用 URL 一样使用 file Uri 方案。资产的语法为 file:///android_asset/...(注意:三个斜杠),其中省略号是 assets/ 文件夹中文件的路径。

There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.

For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.

缱倦旧时光 2024-10-21 19:03:04

正确的 url 是:

file:///android_asset/RELATIVEPATH

其中 RELATIVEPATH 是资源相对于 asset 文件夹的路径。

注意方案中的 3 /。如果没有 3,Web 视图将不会加载我的任何资源。我尝试了 CommonsWare(之前)评论的 2,但它不起作用。然后我查看了 github 上的 CommonsWare 源代码,注意到了额外的正斜杠。

虽然此测试仅在 1.6 Android 模拟器上完成,但我怀疑它在真实设备或更高版本上是否有所不同。

编辑:CommonsWare 更新了他的答案以反映这一微小的变化。所以我编辑了这个,这样它对于他当前的答案仍然有意义。

The correct url is:

file:///android_asset/RELATIVEPATH

where RELATIVEPATH is the path to your resource relative to the assets folder.

Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.

This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.

EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.

独木成林 2024-10-21 19:03:04

最后,我找到了一种从 Kotlin 中的 this 答案获取资产中存在的文件路径的方法。在这里,我们将资产文件复制到缓存并从该缓存文件获取文件路径。

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

获取文件的路径,例如:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath

Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

Get the path to the file like:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath
爱*していゐ 2024-10-21 19:03:04

请尝试此代码工作正常

 Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));

    /* 2) Create a new Intent */
    Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
            .setData(imageUri)
            .build();

Please try this code working fine

 Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));

    /* 2) Create a new Intent */
    Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
            .setData(imageUri)
            .build();
喵星人汪星人 2024-10-21 19:03:04

输入图像描述这里

确保您的资源文件夹放置在正确的位置。

enter image description here

Be sure ,your assets folder put in correct position.

看海 2024-10-21 19:03:04

适用于 WebView,但似乎在 URL.openStream() 上失败。因此,您需要区分 file:// 协议并按照建议通过 AssetManager 处理它们。

Works for WebView but seems to fail on URL.openStream(). So you need to distinguish file:// protocols and handle them via AssetManager as suggested.

早茶月光 2024-10-21 19:03:04

试试这个,它有效:

InputStream in_s = 
    getClass().getClassLoader().getResourceAsStream("TopBrands.xml");

如果您收到空值异常,请尝试这个(使用类 TopBrandData):

InputStream in_s1 =
    TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

Try this out, it works:

InputStream in_s = 
    getClass().getClassLoader().getResourceAsStream("TopBrands.xml");

If you get a Null Value Exception, try this (with class TopBrandData):

InputStream in_s1 =
    TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
诗化ㄋ丶相逢 2024-10-21 19:03:04
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
    
public static String convertStreamToString(InputStream is)
        throws IOException {

    Writer writer = new StringWriter();
    char[] buffer = new char[2048];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    String text = writer.toString();
    return text;
}
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
    
public static String convertStreamToString(InputStream is)
        throws IOException {

    Writer writer = new StringWriter();
    char[] buffer = new char[2048];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    String text = writer.toString();
    return text;
}
岁吢 2024-10-21 19:03:04

试试这个:

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

我已经做到了并且有效

try this :

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat); 

I had did it and it worked

倒带 2024-10-21 19:03:04

由于它实际上是 APK 文件中的数据而不是模拟器上的数据,因此您将无法找到“绝对路径”。我最终以这种非常简单的方式实现了:

private fun getUriFromAsset(context: Context, assetFileName: String): Uri? {
    val assetManager = context.assets
    var inputStream: InputStream? = null
    var outputStream: FileOutputStream? = null
    var tempFile: File? = null

    return try {
        inputStream = assetManager.open(assetFileName)
        tempFile = File.createTempFile("temp_asset", null, context.cacheDir)
        outputStream = FileOutputStream(tempFile)

        inputStream.copyTo(outputStream)

        Uri.fromFile(tempFile)
    } catch (e: IOException) {
        e.printStackTrace()
        null
    } finally {
        inputStream?.close()
        outputStream?.close()
        tempFile?.deleteOnExit()
    }
}

Since it's actually data in the APK file and not on the emulator, you won't be able to find an "absolute path". I've eventually implemented in this pretty straightforward way :

private fun getUriFromAsset(context: Context, assetFileName: String): Uri? {
    val assetManager = context.assets
    var inputStream: InputStream? = null
    var outputStream: FileOutputStream? = null
    var tempFile: File? = null

    return try {
        inputStream = assetManager.open(assetFileName)
        tempFile = File.createTempFile("temp_asset", null, context.cacheDir)
        outputStream = FileOutputStream(tempFile)

        inputStream.copyTo(outputStream)

        Uri.fromFile(tempFile)
    } catch (e: IOException) {
        e.printStackTrace()
        null
    } finally {
        inputStream?.close()
        outputStream?.close()
        tempFile?.deleteOnExit()
    }
}
脱离于你 2024-10-21 19:03:04

是的,您无法从 Android 手机或模拟器访问驱动器文件夹,因为您的计算机和 Android 是两个不同的操作系统。我会选择 Android 的 res 文件夹,因为它具有良好的资源管理方法。除非您有充分的理由将文件放入资产文件夹中。相反你可以这样做

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);
 }

Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

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);
 }
感悟人生的甜 2024-10-21 19:03:04

如果您可以不使用 asset 文件夹,并且希望获取 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://stackoverflow.com/a/57719958

If you are okay with not using assets folder and want to get a URI without storing it in another directory, you can use res/raw directory and create a helper function to get the URI from resID:

internal fun Context.getResourceUri(@AnyRes resourceId: Int): Uri =
    Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(resourceId.toString())
        .build()

Now if you have a mydemo.txt file under res/raw directory you can simply get the URI by calling the above helper method

context.getResourceUri(R.raw.mydemo)

Reference: https://stackoverflow.com/a/57719958

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文