Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 文件绝对路径中的FileNotFoundException(即使文件存在)。为什么?_Java_Eclipse - Fatal编程技术网

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重复:已更正。