Har*_*shG 17 java url uri filepath
我对Java知之甚少.我需要从FilePath(String)
windows 构造一个URI的字符串表示.有时inputFilePath
我得到的是:file:/C:/a.txt
有时是:C:/a.txt
.现在,我正在做的是:
new File(inputFilePath).toURI().toURL().toExternalForm()
Run Code Online (Sandbox Code Playgroud)
以上工作适用于路径,它没有前缀file:/
,但对于前缀为路径的路径file:/
.toURI
方法是通过附加当前dir的值将其转换为无效的URI,因此路径变为无效.
请通过建议正确的方法为这两种路径获取正确的URI来帮助我.
gig*_*dot 12
这些是有效的文件uri:
file:/C:/a.txt <- On Windows
file:///C:/a.txt <- On Windows
file:///home/user/a.txt <- On Linux
Run Code Online (Sandbox Code Playgroud)
因此,您需要删除file:/
或file:///
用于Windows和file://
Linux.
来自https://jaxp.java.net的 SAXLocalNameCount.java :
/**
* Convert from a filename to a file URL.
*/
private static String convertToFileURL ( String filename )
{
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File ( filename ).getAbsolutePath ();
if ( File.separatorChar != '/' )
{
path = path.replace ( File.separatorChar, '/' );
}
if ( !path.startsWith ( "/" ) )
{
path = "/" + path;
}
String retVal = "file:" + path;
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
只需使用 Normalize();
例:
path = Paths.get("/", input).normalize();
Run Code Online (Sandbox Code Playgroud)
这一行将规范您的所有路径。
归档时间: |
|
查看次数: |
62575 次 |
最近记录: |