URL.getFile()中的错误 [英] Error in URL.getFile()
问题描述
我正在尝试从URL打开文件.
I am trying to open a file from URL.
URL的对象是使用ClassLoader的getResource()方法创建的. 从getResource()方法返回的输出URL是=
Object of URL is created with getResource() method of ClassLoader. Output URL returned from getResource() method is =
file:/C:/users/
使用URL.getFile()方法返回String为"/C:/users/"后,它将删除"文件:",而不会删除"/" 这使我在使用新的FileInputStream打开文件时出现错误. 错误:FileNotFoundException
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
"/"导致获取路径对象时出现相同的问题. 在这里,目录值是从URL.getResource().getFile()
" / " 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()
路径目标= Paths.get(目录);
Path Dest = Paths.get(Directory);
收到的错误是: java.nio.file.InvalidPathException:索引2处的非法字符<:>:/C:/Users/
有人面对这样的问题吗?
is anyone face such issue ?
推荐答案
不使用URL.getFile()
,它返回URL的文件"部分,该部分与文件或文件的路径名不同在磁盘上. (看起来很像,但是您发现有很多不匹配的方法.)相反,调用URL.toURI()
并将生成的URI对象传递给Paths.get()
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()
只要您的URL指向一个真实文件而不是jar文件中的资源,那该行得通.
That should work, as long as your URL points to a real file and not to a resource inside a jar file.
示例:
URL url = getClass().getResource("/some/resource/path");
Path dest = Paths.get(url.toURI());
这篇关于URL.getFile()中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!