navige
navige

Reputation: 2517

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?

Upvotes: 28

Views: 16591

Answers (2)

pangiole
pangiole

Reputation: 991

In Scala would be

import java.nio.file.Paths

val resource = getClass.getResource("myfile.txt")
val path = Paths.get(resource.toURI)

In Java should be the same (with slightly different syntax)

Upvotes: 0

Lolo
Lolo

Reputation: 4347

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.

Upvotes: 38

Related Questions