Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid java.net.URISyntaxException in URL.toURI()

Tags:

java

url

uri

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?

like image 920
Andrew Eisenberg Avatar asked Dec 20 '10 21:12

Andrew Eisenberg


People also ask

How to convert URL to URI in Java?

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.

What is toURI in Java?

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()).

What is URISyntaxException?

public class URISyntaxException extends Exception. Checked exception thrown to indicate that a string could not be parsed as a URI reference.


1 Answers

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();
}
like image 76
axtavt Avatar answered Oct 20 '22 20:10

axtavt