我对 Java 知之甚少。我需要在 Windows 上从 FilePath(String)
构建 URI 的字符串表示形式。有时,我得到的 inputFilePath
是:file:/C:/a.txt
,有时是:C:/a.txt
。现在,我正在做的是:
new File(inputFilePath).toURI().toURL().toExternalForm()
以上对于没有file:/
前缀的路径工作正常,但是对于以file:/
为前缀的路径,.toURI
方法通过附加当前目录的值将其转换为无效的 URI,因此路径变得无效。
请通过建议一种正确的方法来帮助我为这两种路径获取正确的 URI。
最佳答案
这些是有效的文件 uri:
file:/C:/a.txt <- On Windows
file:///C:/a.txt <- On Windows
file:///home/user/a.txt <- On Linux
因此您需要删除 Windows 的 file:/
或 file:///
和 Linux 的 file://
。
关于Java:从文件路径获取 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8323760/