Error in URL.getFile()

最后都变了- 提交于 2019-12-10 12:55:15

问题


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 ?


回答1:


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



回答2:


The problem is that your result path contains leading /.

Try:

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


来源:https://stackoverflow.com/questions/21398699/error-in-url-getfile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!