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

And*_*erg 10 java url uri

在一个特定的程序中,我传递了一个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
Run Code Online (Sandbox Code Playgroud)

执行此转换的最佳方法是什么,以便处理所有特殊字符?

axt*_*avt 7

我想最好的方法是删除File.toURL()通常负责产生这些错误URL的弃用.

如果你不能这样做,这样的事情可能会有所帮助:

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