user3243318
user3243318

Reputation: 101

Error in URL.getFile()

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 ?

Upvotes: 10

Views: 6142

Answers (2)

am0wa
am0wa

Reputation: 8377

The problem is that your result path contains leading /.

Try:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
Path path = Paths.get(loader.getResource(filename).toURI());

Upvotes: 2

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

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());

Upvotes: 14

Related Questions