簡體   English   中英

如何避免URL.toURI()中的java.net.URISyntaxException

[英]How to avoid java.net.URISyntaxException in URL.toURI()

在一個特定的程序中,我傳遞了一個file: URL,我需要將其轉換為URI對象。 如果URL中有空格或任何其他無效字符,則使用toURI方法將拋出java.net.URISyntaxException

例如:

URL url = Platform.getInstallURL();  // file:/Applications/Program
System.out.println(url.toURI());  // prints file:/Applications/Program

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(url.toURI());  // throws java.net.URISyntaxException because of the space

執行此轉換的最佳方法是什么,以便處理所有特殊字符?

我想最好的方法是刪除已棄用的File.toURL() ,它通常負責生成這些不正確的URL。

如果你不能這樣做,這樣的事情可能會有所幫助:

public static URI fixFileURL(URL u) {
    if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException();
    return new File(u.getFile()).toURI();
}

我遇到了同樣的問題。 在我看來,最好的解決方案是使用URI對象的重載構造函數,並用URL對象的getter填充它。 這樣,URI構造函數就會處理path-url-encoding本身,並且不會觸及其他部分(如協議“http://”之后的斜杠)。

uri = new URI(url.getProtocol(), url.getAuthority(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());

不應設置的字段可以填充null。

這是未經測試的,但您可以有效地執行此操作:

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(new URI(URLEncoder.encode(url.toString(), "UTF-8"))); 

或者,你可以這樣做:

System.out.println(new URI(url.toString().replace(" ", "%20")));

暫無
暫無

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

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