Java – Converts URLs to paths without throwing exceptions

Converts URLs to paths without throwing exceptions… here is a solution to the problem.

Converts URLs to paths without throwing exceptions

A common scenario I’m having is when I want to do some IO on local resources in my project. The easiest way to access a local resource is getClass().getResource("path"), which returns a URL. * The easiest way to access IO content is through Files.XXX most of the time java.nio.Path is required.

Converting URLs to paths is easy: Paths.get(url.toURI()). Unfortunately, this may throw a URISyntaxException that I have to catch now. I don’t understand why, it’s annoying, ugly, I’ve never got it, I hate it.

Now the real question is: is there another way to access a local resource as a path or convert a URL to a path without throwing an exception?


  • I know there is also getResourceAsStream(), but a simple InputStream is usually not enough.

Solution

Look at the Javadoc for URL.toURI() and you’ll see :

Returns a URI equivalent to this URL . This method functions in the same way as new URI (this.toString()).

This method is the same as calling the URI(String) constructor, which is the source of a possible URISyntaxException. However, if you look at the URI class, you’ll find a static factory method: URI.create(String) The Javadoc for this method states:

Creates a URI by parsing the given string.

This convenience factory method works as if by invoking the URI(String) constructor; any URISyntaxException thrown by the constructor is caught and wrapped in a new IllegalArgumentException object, which is then thrown.

This means that both URL.toURI() and URI.create(String) call the new URI(String). The difference is that URI.create(String) throws an unchecked IllegalArgumentException, which means you don’t have to use try-catch blocks everywhere. You can use the following:

URL resource = getClass().getResource("/path/to/resource");
Path path = Paths.get(URI.create(resource.toString())); 

Related Problems and Solutions