我想知道是否可以将 file://
前缀硬核到我在 android 中的一个函数中。
该函数应该确定给定的链接是否指向网络上的外部资源,或者手机本身的内部资源
public Uri generate_image_uri(String link)
{
// link can be "1DCHiI2.jpg"
// link can be "file://smiley_face.jpg"
if (!link.startsWith("file://")
return Uri.parse("https://i.imgur.com/" + link);
else
return Uri.parse(link);
}
这是可取的吗?或者是否有一种更“容错”的方式来获取 file://
?可能是像 getProperFilePrefixForThisAndroidVersion();
这样的函数?
为了澄清我的问题:
给出以下代码
(new File(getFilesDir(), "hello_world.jpg")).toString();
可以在合理的概率内安全地假设,在所有当前和 future 的 Android 版本中,生成的字符串始终以 file://
开头吗?
最佳答案
Given:
(new File(getFilesDir(), "hello_world.jpg")).toString();
is it safe to assume within reasonable probability that the resulting string will always start with file:// in all current and future Android versions?
没有。
根据 Android 上 File
的 javadoc,File.toString 返回:
"... the pathname string of this abstract pathname. This is just the string returned by the getPath() method."
不是“file://”URL。
如果您想获得格式正确的“file://”URL,请执行以下操作:
new File(...).toURI().toString()
现在,技术上 URL(即"file")的协议(protocol)不区分大小写:
这意味着“FILE://”或“File://”等在技术上是有效的替代方案。
但是,上述表达式永远发出除协议(protocol)小写形式之外的任何内容的概率非常小1。
1 - 这将导致许多人做出极其愚蠢的决定。他们不是愚蠢的人。
关于java - `file://` uri 前缀是我可以硬编码的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48054795/