[英]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.