简体   繁体   English

Java:从FilePath获取URI

[英]Java: Get URI from FilePath

I've little knowledge of Java. 我对Java知之甚少。 I need to construct a string representation of an URI from FilePath(String) on windows. 我需要在Windows上从FilePath(String)构造一个URI的字符串表示。 Sometimes the inputFilePath I get is: file:/C:/a.txt and sometimes it is: C:/a.txt . 有时我得到的inputFilePath是: file:/C:/a.txt ,有时它是: C:/a.txt Right now, what I'm doing is: 现在,我正在做的是:

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

The above works fine for paths, which are not prefixed with file:/ , but for paths prefixed with file:/ , the . 上面的方法适用于路径,它不带有file:/前缀,但对于带有file:/前缀的路径file:/ ,。 toURI method is converting it to a invalid URI, by appending value of current dir, and hence the path becomes invalid. toURI方法通过附加当前dir的值将其转换为无效的URI,因此路径变为无效。

Please help me out by suggesting a correct way to get the proper URI for both kind of paths. 请通过建议正确的方法为这两种路径获取正确的URI来帮助我。

These are the valid file uri: 这些是有效的文件uri:

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

So you will need to remove file:/ or file:/// for Windows and file:// for Linux. 因此,您需要删除file:/file:/// for Windows和file:// for Linux。

From SAXLocalNameCount.java from https://jaxp.java.net : 来自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;
}

Just use Normalize(); 只需使用Normalize();

Example: 例:

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

this one line will normalize all your paths. 这一行将规范你的所有路径。

The argument to new File(String) is a path, not a URI. new File(String)的参数是路径,而不是URI。 The part of your post after 'but' is therefore an invalid use of the API. 因此,“但是”之后的帖子部分是对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);
    }
}

Gives output: 给出输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM