如何避免 URL.toURI() 中的 java.net.URISyntaxException
在特定程序中,我传递了一个 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
执行此转换以便处理所有特殊字符的最佳方法是什么?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想最好的方法是删除已弃用的
File.toURL()
,它通常负责生成这些不正确的 URL。如果你做不到,这样的事情可能会有所帮助:
I guess the best way would be to remove deprecated
File.toURL()
which is usually responsible for producing these incorrect URLs.If you can't do it, something like this may help:
我也遇到过同样的问题。我认为最好的解决方案是使用 URI 对象的重载构造函数,并用 URL 对象的 getter 填充它。这样,URI 构造函数会处理路径 url 编码本身,而其他部分(例如协议“http://”后面的斜杠)将不会被触及。
不应设置的字段可以用 null 填充。
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.
Fields that should not be set could be filled with null.
这是未经测试,但您可以有效地执行此操作:
或者,您可以执行此操作:
This is untested but you could, effectively, do this:
Alternatively, you could do this: