Search code examples
niojava-7

Java 7: get Path of resource (as object of type Path)


I'm using the features of Java 7 to read in a file. For that purpose I need an object of type Path. In my code, I use the getResource() function to get the relative path (of type URL) to a file.

However, now I have the problem that I don't really now how to get from an object of type URL to an object of type Path easily (without having to go through castings to e.g. to URI then to File and from that to Path)?

Here an example to show you what I would like to do:

URL url = getClass().getResource("file.txt");
Path path = (new File(url.toURI())).toPath(); //is there an easier way?
List<String> list = Files.readAllLines(path, Charset.defaultCharset());

So is there an easier way to achieve that and not having to do that code mess on line 2?


Solution

  • How about

    Path path = Paths.get(url.toURI());
    

    It is not proper to create a File from your URL, since it's gotten from the classpath and the file may actually be within a jar.