Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java-7

nio

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?

like image 970
navige Avatar asked May 28 '13 16:05

navige


People also ask

How do you get a path to a resource in a Java?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.

What is getAbsolutePath in Java?

The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.

How do I read a resource folder in eclipse?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().


1 Answers

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.

like image 81
Lolo Avatar answered Oct 02 '22 14:10

Lolo