Java中使用getClass().getResource()获取文件路径失效问题求助
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:
Use an absolute classpath path
Add a leading/to the path to tellgetResource()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!"); } }Use the ClassLoader's
getResource()method
The ClassLoader'sgetResource()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

