Java:从 FilePath 获取 URI [英] Java: Get URI from FilePath
问题描述
我对Java知之甚少.我需要从 Windows 上的 FilePath(String)
构造一个 URI 的字符串表示.有时我得到的 inputFilePath
是:file:/C:/a.txt
有时是:C:/a.txt
.现在,我正在做的是:
I've little knowledge of Java. I need to construct a string representation of an URI from FilePath(String)
on windows. Sometimes the inputFilePath
I get is: file:/C:/a.txt
and sometimes it is: C:/a.txt
. Right now, what I'm doing is:
new File(inputFilePath).toURI().toURL().toExternalForm()
以上适用于不以 file:/
为前缀的路径,但对于以 file:/
为前缀的路径,.toURI
方法通过附加当前目录的值将其转换为无效的 URI,因此路径变得无效.
The above works fine for paths, which are not prefixed with file:/
, but for paths prefixed with file:/
, the .toURI
method is converting it to a invalid URI, by appending value of current dir, and hence the path becomes invalid.
请帮我建议一个正确的方法来为这两种路径获取正确的 URI.
Please help me out by suggesting a correct way to get the proper URI for both kind of paths.
推荐答案
这些是有效的文件 uri:
These are the valid file uri:
file:/C:/a.txt <- On Windows
file:///C:/a.txt <- On Windows
file:///home/user/a.txt <- On Linux
因此您需要删除 file:/
或 file:///
(对于 Windows)和 file://
(对于 Linux).
So you will need to remove file:/
or file:///
for Windows and file://
for Linux.
这篇关于Java:从 FilePath 获取 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!