1

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.

jilt3d
  • 3,864
  • 8
  • 34
  • 41

2 Answers2

1

You could use:

final File file = new File(fileURL.getFile());
final Path path = file.toPath(); //can throw an unchecked exception
assylias
  • 321,522
  • 82
  • 660
  • 783
  • That is an option but the code becomes a bit unreadable (or let say confusing). I would like to use only the new API (without going through the old one). – jilt3d Aug 28 '13 at 11:32
  • BTW, this raises a few questions - why most of the getResource() methods return URLs, and on the other hand factory methods for creating Path requires URI as the constructor of File does the same? – jilt3d Aug 28 '13 at 11:37
  • I've tried that - doesn't work. It throws InvalidPathException: Illegal char <:> at index 4. It seems the : symbol is not allowed in the String argument of Paths.get(String). It is also the documentation is not enough specific about how the argument should look like. – jilt3d Aug 28 '13 at 12:27
  • Nope. It throws the same exception (but with different index of the illegal character). – jilt3d Aug 28 '13 at 12:40
0

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);
jilt3d
  • 3,864
  • 8
  • 34
  • 41