You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用getClass().getResource()获取文件路径失效问题求助

Why getResource() Can't Find Your Resource File

Hey there, let's break down why your code isn't locating the serverConf.xml file correctly, even though the manual relative path works.

The Root Cause

When you use this.getClass().getResource("config/serverConf.xml"), the method looks for the resource relative to the package of your Main class, not from the root of the classpath.

For example, if your Main class is in a package like com.myproject, it will actually try to find com/myproject/config/serverConf.xml in the classpath— which doesn't exist, since your config is directly under src/main/resources/config/.

On the other hand, the manual path src/main/resources/config/serverConf.xml works in your IDE because the project root is set as the working directory. But this approach will fail once you package your project into a JAR, since the src directory won't exist in the final artifact.

Fixes to Try

Here are two reliable ways to access your resource correctly:

  1. Use an absolute classpath path
    Add a leading / to the path to tell getResource() to start searching from the root of the classpath:

    public Main(){
        URL resourceUrl = this.getClass().getResource("/config/serverConf.xml");
        if (resourceUrl != null) {
            File file = new File(resourceUrl.getPath());
            if(file.exists())
                System.out.println("Yes");
            else
                System.out.println("No");
        } else {
            System.out.println("Resource not found!");
        }
    }
    
  2. Use the ClassLoader's getResource() method
    The ClassLoader's getResource() method defaults to searching from the classpath root, so you don't need the leading /:

    public Main(){
        URL resourceUrl = this.getClass().getClassLoader().getResource("config/serverConf.xml");
        if (resourceUrl != null) {
            File file = new File(resourceUrl.getPath());
            if(file.exists())
                System.out.println("Yes");
            else
                System.out.println("No");
        } else {
            System.out.println("Resource not found!");
        }
    }
    

Important Note

Once you package your project, the resource files will be placed directly in the classpath (under config/ in your case), so using the classpath-based approach will work both in your IDE and in the packaged JAR. Avoid relying on file system paths like src/main/resources/— those are only valid during development.

内容的提问来源于stack exchange,提问作者alex_z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:48:32