Java:从文件路径获取URI

21

我对Java知识了解不多,我需要从 FilePath(String) 构造一个URI的字符串表示,该文件路径在Windows上。有时候我得到的 inputFilePath 是: file:/C:/a.txt ,有时候是: C:/a.txt 。目前,我的做法是:

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

对于没有以file:/为前缀的路径,上述方法很好用,但对于以file:/为前缀的路径,.toURI方法会将其转换为一个无效的URI,并附加当前目录的值,从而使路径变得无效。

请帮我找出一种正确的方法,以获取两种类型路径的正确URI。


1
如果只需要从字符串开头删除file:/,这样是否就足够了呢?或者可能存在其他有效的前缀吗? - Thomas
5个回答

15

以下是有效的文件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)。


6

只需使用 Normalize(); 函数即可。

例子:

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

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


哪个更好 - 1. new File(inputFilePath).toURI() 还是 2. Paths.get(inputFilePath).toUri() ? - Gaurav
1
@gaurav 在这种情况下,Paths.get() 会提供类似的结果,但因为我们不必创建一个 FIle 对象,第二个选项可能更好。 - william.eyidi

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;
}

5
自Java SE7以来,以下一行代码返回了如下的结果:java.nio.file.FileSystems.getDefault().getPath( xmlFileAsString ).toAbsolutePath().toUri(),例如返回 "file:///C:/develop/doku/projects/Documentry/THB/src/docbkx/Systemvoraussetzungen.xml" - udoline
@udoline Paths.get(xmlFileAsString) 是正确的方法。它在内部执行相同的操作。 - Lii
在调用.toUri()之前,.toAbsolutePath()方法是否必要? - Gaurav

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

那么,我应该如何将URI转换为路径呢?基本上,要获取一个不以"file:"为前缀的路径。 - HarshG
@user1073005 new URI(uri).getPath(),但这是一个新问题,不是吗?你上面的问题是关于如何“构造URI的字符串表示形式”。 - user207421
哪个更好 - 1. new File(inputFilePath).toURI() 还是 2. Paths.get(inputFilePath).toUri()? - Gaurav

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

我建议使用Apache Commons的StringUtils.removeStart(...)函数:brokenPath = StringUtils.removeStart(brokenPath, "file:/") - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接