Java 文件绝对路径中的FileNotFoundException(即使文件存在)。为什么?
我正试图通过使用Java 文件绝对路径中的FileNotFoundException(即使文件存在)。为什么?,java,eclipse,Java,Eclipse,我正试图通过使用ClassLoader的绝对路径从我的程序访问位于(src/main/resources/test.gif)的文件test.gif,方法如下 String absPath=this.getClass().getResource("/test.gif").toString(); System.out.print(Path);// prints the absolute path /Users/Abby/Project/SubFolder/ProjectName/target/cla
ClassLoader
的绝对路径从我的程序访问位于(src/main/resources/test.gif
)的文件test.gif
,方法如下
String absPath=this.getClass().getResource("/test.gif").toString();
System.out.print(Path);// prints the absolute path /Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif - the file exists at the location.
String relPath= "src/main/resources/test.gif";
但是,访问absPath
会在我的程序中导致FileNotFoundException,而使用relPath
则不会
我到底做错了什么?如何使用绝对路径(通过类加载器)正确访问文件你说的是相对路径,但是你用“/test.gif”测试的路径以/开头,为什么! 在添加新问题之前,请查看其他回复。
使用URL和文件类:
URL url = getClass().getResource("/test.gif");
File file = new File(url.toURI();
System.out.println(file).getCanonicalPath());
此外,getCanonicalPath()将返回文件的绝对路径。
如果找不到资源,您可能需要检查null。如果这
Users/[username]/Project/SubFolder
是正确的绝对路径,那么它缺少一个前导斜杠。Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif
不是绝对路径-至少您缺少了,开头有一个/
。可能与@Mureinik重复:已更正。