Spring Boot 2.1.5.RELEASE here. I'm trying to load a resource from a src/main/resources/images
directory. My best attempt thus far is:
URL url = getClass().getResource("classpath:images/my_logo.png");
if (url == null) {
log.warn("Hmmm not found...");
} else {
log.info("Found it!");
}
At runtime the WARNing " Hmmm not found... " is printing, but the file is absolutely located at src/main/resources/images/my_logo.png
. Where am I going awry?
Since you are already using Spring, try using one of their resource loaders
URL url = new PathMatchingResourcePatternResolver( null ).getResource( "classpath:/images/my_logo.png" ).getURL();
Notice: I added a leading slash to the path.
EDIT : I did check on @duffymo's comment and it was correct. The leading slash is not necessary.
There is also another way to retrieve resources in Spring, but the ResourceUtils Javadoc is clear that the class is mainly for internal use.
String file = ResourceUtils.getFile("images/my_logo.png").getAbsolutePath();
Or by using ClassPathResource
URL clsPath = new ClassPathResource("images/my_logo.png").getURL();
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.