簡體   English   中英

Java:從FilePath獲取URI

[英]Java: Get URI from FilePath

我對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。 因此,“但是”之后的帖子部分是對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 . . .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM