Java:从FilePath获取URI

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.


Lyl*_*e Z 5

来自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)

  • 因为JavaSE7做了那一行...`java.nio.file.FileSystems.getDefault().getPath(xmlFileAsString).toAbsolutePath().toUri()`返回例如.` "文件:/// C:/develop/doku/projects/Documentry/THB/src/docbkx/Systemvoraussetzungen.xml"` (5认同)

wil*_*idi 5

只需使用 Normalize();

例:

path = Paths.get("/", input).normalize();
Run Code Online (Sandbox Code Playgroud)

这一行将规范您的所有路径。