Java - 使用 getClass().getResource() 的文件路径不起作用

标签 java file relative-path

我一直在阅读此处和 Quora 上提出的相同问题,但是,我仍然不明白为什么我无法访问位于“src/main/resources”文件夹中的文件。 当我手动指定相对路径“src/main/resources/config/serverConf.xml”时,一切正常

项目结构:

src/main/java/"project related folders"
src/main/resources/config/serverConf.xml

主类:

public class Main{

    public Main(){
        File file = new File(this.getClass().getResource("config/serverConf.xml").getPath());
        if(file.exists())
            System.out.println("Yes");
        else
            System.out.println("No");
    }

    public static void main(String[] args){
        Main main = new Main();
    }
}

最佳答案

"config/serverConf.xml"

应该是

"/config/serverConf.xml"

关于Java - 使用 getClass().getResource() 的文件路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50631088/

相关文章:

c - 我的 while 循环上的错误代码,试图逐行读取文件。在C中

python - 在通过 for 循环创建内容时检查 csv 文件

css - JSP 和 Spring 应用程序

java - JFreeChart 中的差距

java - Spring Data Repository JPA 实体继承问题 : Cannot instantiate abstract class or interface

java - SWT在windows上哪里写dll文件?

c - 在 fread(3) 中检查读取的项目数是否小于请求的数量,而不是 0,是否正确?

R:source() 和源文件的路径

java - 如何比较两个不同数组中的字符串组件 (Java)