Get rid of a checked exception when using NIO2 API

216 views Asked by At

Currently, I was loading a property file from the classpath using the following code with the help of Guava API:

final URL fileURL = Resources.getResource("res.properties");
final File file = new File(fileURL.getFile());

I decided to give a try the new NIO2 API introduced in Java7SE and remove any Guava API calls so I transformed the code to the following:

final URL fileURL = getClass().getResource("/res.properties");
final Path path = Paths.get(fileURL.toURI());

But the modified code throws a checked exception in the line where conversion occurs between URL and URI. Is there any way I can get rid of it. Can I get a Path instance with given URL, for example?

P.S. I am aware that the modified code is not semantically the same as the original one - Guava's getResource throws IllegalArgumentException if resources is not found, the Java's getResource returns null in this case.

2

There are 2 answers

4
assylias On

You could use:

final File file = new File(fileURL.getFile());
final Path path = file.toPath(); //can throw an unchecked exception
0
jilt3d On

Here is what I found:

final URL fileURL = getClass().getResource("/res.properties");
final URI fileURI = URI.create(fileURL.toString());
final Path path = Paths.get(fileURI);