Java:从FilePath获取URI

我对Java知之甚少。 我需要在Windows上从FilePath(String)构造一个URI的字符串表示。 有时我得到的inputFilePath是: file:/C:/a.txt ,有时它是: C:/a.txt 。 现在,我正在做的是:

 new File(inputFilePath).toURI().toURL().toExternalForm() 

上面的方法适用于没有file:/前缀的路径,但对于带有file:/前缀的路径file:/ ,。 toURI方法通过附加当前dir的值将其转换为无效的URI,因此路径变为无效。

请通过建议正确的方法为这两种路径获取正确的URI来帮助我。

这些是有效的文件uri:

 file:/C:/a.txt <- On Windows file:///C:/a.txt <- On Windows file:///home/user/a.txt <- On Linux 

因此,您需要删除file:/file:/// for Windows和file:// for 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; } 

只需使用Normalize();

例:

 path = Paths.get("/", input).normalize(); 

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

new File(String)的参数是路径,而不是URI。 因此,“但是”之后的post部分是对API的无效使用。

 class TestPath { public static void main(String[] args) { String brokenPath = "file:/C:/a.txt"; System.out.println(brokenPath); if (brokenPath.startsWith("file:/")) { brokenPath = brokenPath.substring(6,brokenPath.length()); } System.out.println(brokenPath); } } 

给出输出:

 file:/C:/a.txt C:/a.txt Press any key to continue . . .