Android:如何找到assets文件夹的绝对路径?
我需要获取应用程序中资产文件夹的绝对路径,因为我想使用网络服务器提供文件,并且它需要绝对路径。这可能吗?
我本以为可能会有这样的事情:
String rootDir = getAssets().getRootDirectory();
但没有。
任何帮助表示赞赏,干杯。
I need to get the absolute path of the assets folder in my app as I want to serve the files within using a webserver and it needs the absolute path. Is this possible?
I would have thought there might be something like this:
String rootDir = getAssets().getRootDirectory();
but there's not.
Any help appreciated, cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。没有“[您的]应用程序中资产文件夹的绝对路径”。资产存储在 APK 文件中。
在某些情况下,例如提供给
WebView
的 URL,您可以使用特殊的file:///android_asset
基本 URL 来引用资源中的文件。No. There is no "absolute path of the assets folder in [your] app". Assets are stored in the APK file.
In select cases, such as URLs supplied to a
WebView
, you can use the specialfile:///android_asset
base URL to reference files in your assets.您始终可以将文件从 APK 中的资产目录复制到设备上的文件夹,然后提供该文件夹。
You can always copy files from the assets directory in the APK to a folder on the device, then serve that folder.
正如提到的,Android 资源无法通过设备文件系统中的绝对路径进行访问。因此,每当您必须为方法提供文件系统路径时,您就不走运了。
但是,根据您的情况,还有其他选项:
仅当您希望使用网络服务器为此提供的默认机制将文件作为静态文件提供时,才需要绝对路径。但网络服务器更加灵活:您可以将 URL 中的任何路径映射到您可以访问的任何数据源:文件、数据库、Web 资源、Android 资源、Android 资产。如何执行此操作取决于您使用的 Web 服务器。
例如,您可以自己定义任何以
https://example.com/assets/
开头的 URL 应映射到 Android APK 的 asset 文件夹。然后,您可以将资产作为InputStream
打开,并将内容提供给网络服务器的客户端。As mentioned, Android assets cannot be accessed with absolute paths in the device file system. So whenever you have to provide a filesystem path to a method, you're out of luck.
However, in your case there are additional options:
Needing the absolute path is only true if you want to serve the file as a static file with the default mechanism a webserver provides for that. But webservers are much more flexible: you an map any path in an URL to any data source you can access: files, databases, web resources, Android resources, Android assets. How to do that depends on the web server you use.
For example, you can define for youself that any URL starting with
https://example.com/assets/
should be mapped to the assets folder of your Android APK. You can then open the asset as anInputStream
and serve the content to the webserver's client.如果您有任何资产(例如 PDF 文件)存储在资产文件夹中,请使用以下行获取其路径:
If you have any asset like PDF file stored inside assets folder then get its path using below line: