I am trying to open a file from URL.
Object of URL is created with getResource() method of ClassLoader. Output URL returned from getResource() method is =
file:/C:/users/
After using URL.getFile() method which returns String as " /C:/users/ " it removes "file:" only not the "/ " This / gives me a error in opening a file using new FileInputStream. Error : FileNotFoundException
" / " in the starting of the filename causes the same problem in getting the path object. Here , value of directory is retrieved from the URL.getResource().getFile()
Path Dest = Paths.get(Directory);
Error received is : java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/Users/
is anyone face such issue ?
URL getFile() method in Java with Examples The getFile() function is a part of URL class. The function getFile() returns the file name of a specified URL. The getFile() function returns the path and the query of the URL.
Don't use URL.getFile()
, it returns the "file" part of the URL, which is not the same as a file or path name of a file on disk. (It looks like it, but there are many ways in which there is a mismatch, as you have discovered.) Instead, call URL.toURI()
and pass the resulting URI object to Paths.get()
That should work, as long as your URL points to a real file and not to a resource inside a jar file.
Example:
URL url = getClass().getResource("/some/resource/path");
Path dest = Paths.get(url.toURI());
The problem is that your result path contains leading /
.
Try:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Path path = Paths.get(loader.getResource(filename).toURI());
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