2011-11-30 63 views
12

我对Java很少了解。我需要在窗口上构建一个来自FilePath(String)的URI的字符串表示。有时我得到的inputFilePath是:file:/C:/a.txt,有时它是:C:/a.txt。现在,我在做什么是:Java:从FilePath获取URI

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

以上工作正常的路径,这是不以file:/前缀,但路径前缀file:/的。 toURI方法通过附加当前目录的值将其转换为无效的URI,因此该路径变为无效。

请帮助我通过建议一种正确的方式来获得这两种路径的正确的URI。

+1

只要从字符串的开头删除'file:/'(如果存在)就足够了吗?或者可能还有其他有效的前缀? – Thomas

回答

11

这些都是有效的文件URI:

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

所以,你将需要删除的Win​​dows file:/file:///file://的Linux版本。

1

new File(String)的参数是一个路径,而不是URI。 'but'后的帖子部分因此是API的无效使用。

+0

那么我该怎么做才能将URI转换为路径?从本质上讲,要得到一个没有以“file:” – HarshG

+0

@ user1073005'new URI(uri).getPath()'为前缀的路径,但这是一个新问题,不是吗?上面的问题是关于如何“构建URI的字符串表示”。 – EJP

+0

对不起,我的... – HarshG

0
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 . . . 
+0

我建议使用Apache Commons的''StringUtils.removeStart(...)':'brokenPath = StringUtils.removeStart(brokenPath,“file:/”)'。 – Thomas

4

从SAXLocalNameCount.java从https://jaxp.java.net

/** 
* 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; 
} 
+0

令人惊叹,作品像一个魅力! – Andrei

+3

因为JavaSE7做这一行... \t \t 'java.nio.file.FileSystems.getDefault()的getPath(xmlFileAsString).toAbsolutePath()。toUri()' \t \t 返回如。 ' “文件:/// C:/develop/doku/projects/Documentry/THB/src/docbkx/Systemvoraussetzungen.xml”' – udoline

3

只需使用Normalize();

例子:

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

这一行会正常化所有的路径。