如何避免 URL.toURI() 中的 java.net.URISyntaxException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4494063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to avoid java.net.URISyntaxException in URL.toURI()
提问by Andrew Eisenberg
In a particular program, I am passed a file:
URL and I need to convert it to a URI
object. Using the toURI
method will throw a java.net.URISyntaxException
if there are spaces or any other invalid characters in the URL.
在一个特定的程序中,我传递了一个file:
URL,我需要将它转换为一个URI
对象。如果 URL 中有空格或任何其他无效字符,则使用该toURI
方法将抛出 a java.net.URISyntaxException
。
For example:
例如:
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
What is the best way of performing this conversion so that all special characters are handled?
执行此转换以便处理所有特殊字符的最佳方法是什么?
采纳答案by axtavt
I guess the best way would be to remove deprecated File.toURL()
which is usually responsible for producing these incorrect URLs.
我想最好的方法是删除 deprecatedFile.toURL()
通常负责产生这些不正确的 URL。
If you can't do it, something like this may help:
如果你做不到,这样的事情可能会有所帮助:
public static URI fixFileURL(URL u) {
if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException();
return new File(u.getFile()).toURI();
}
回答by mlemler
I've had the same problem. The best solution in my opinion is to use the overloaded constructor for the URI object and fill it with the getters of the URL object. This way the URI constructor handles the path-url-encoding itself and other parts (like the slashes in after the protocol "http://") will not be touched.
我遇到了同样的问题。我认为最好的解决方案是对 URI 对象使用重载的构造函数,并用 URL 对象的 getter 填充它。这样,URI 构造函数会自行处理路径 url 编码,其他部分(如协议“http://”之后的斜杠)将不会被触及。
uri = new URI(url.getProtocol(), url.getAuthority(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
Fields that should not be set could be filled with null.
不应设置的字段可以填充为 null。
回答by Buhake Sindi
This is untestedbut you could, effectively, do this:
这是未经测试的,但您可以有效地执行以下操作:
URL url = Platform.getConfigurationURL(); // file:/Users/Andrew Eisenberg
System.out.println(new URI(URLEncoder.encode(url.toString(), "UTF-8")));
Alternatively, you could do this:
或者,您可以这样做:
System.out.println(new URI(url.toString().replace(" ", "%20")));