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?
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.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With