简体   繁体   中英

How to properly get resource Java project

In my project i currently have a setup using eclipse

在此处输入图片说明

But when i try to load the file "bg.png" by calling getClass().getResource("/res/bg.png") or getClass().getResourceAsStream("/res/bg.png") I get a NPE

Can anyone tell me whats happening here? I never really thought there was much difference between how both methods locate their files

TIA

getClass().getResource[AsStream]() uses the class loader to load resources: the same mechanism as the one used to load class files based on the classpath.

So, to be able to load the resource, it must be in a jar file or under a directory that is part of the classpath. That is not the case here.

Move the res directory to the src directory: the file will then be in an Eclipse source directory, and Eclipse will "compile" it by simply copying the file to its bin/classes/whatever destination directory, which is in the classpath when running the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM