Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in URL.getFile()

Tags:

java-7

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 ?

like image 206
user3243318 Avatar asked Jan 28 '14 06:01

user3243318


People also ask

What is getFile in Java?

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.


2 Answers

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());
like image 113
Erwin Bolwidt Avatar answered Nov 04 '22 00:11

Erwin Bolwidt


The problem is that your result path contains leading /.

Try:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
Path path = Paths.get(loader.getResource(filename).toURI());
like image 42
am0wa Avatar answered Nov 03 '22 22:11

am0wa