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?
The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format.
Java URL toURI() method The toURI() method returns URI equivalent to given URL. This method functions in the same way as new URI (this. toString()).
public class URISyntaxException extends Exception. Checked exception thrown to indicate that a string could not be parsed as a URI reference.
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:
public static URI fixFileURL(URL u) {
if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException();
return new File(u.getFile()).toURI();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With