Main Tutorials

Spring – Read file from resources folder

In Spring, we can use ClassPathResource or ResourceLoader to get files from classpath easily.

P.S Tested with Spring 5.1.4.RELEASE

1. src/main/resources/

For example, an image file in the src/main/resources/ folder

resources

2. ClassPathResource


import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.InputStream;

	Resource resource = new ClassPathResource("android.png");

	InputStream input = resource.getInputStream();

	File file = resource.getFile();

3. ResourceLoader


import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.io.InputStream;


	@Autowired
    ResourceLoader resourceLoader;
	
	Resource resource = resourceLoader.getResource("classpath:android.png");

	InputStream input = resource.getInputStream();

	File file = resource.getFile();

4. ResourceUtils

Please DO NOT use this ResourceUtils even it works, this class is mainly for internal use within the framework. Read the ResourceUtils JavaDocs


import org.springframework.util.ResourceUtils;

	File file = ResourceUtils.getFile("classpath:android.png");

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
emrah
4 years ago

Hi, I’m using ClassPathResource and ResourceLoader but I am get error : class path resource [image.png] cannot be opened because it does not exist

springrocks
4 years ago
Reply to  emrah

me too..

Andreas Alme
4 years ago

Is it possible to store folder with files under resources?

Sumanth
1 year ago

Trying to access my resource file in jar. Its working if i’m running from IDE but if i’m running the jar then giving an issue. java.io.FileNotFoundException: class path resource [iam-jks-1.4.5.jks] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/test/Documents/event-ingestion-service/target/event-ingestion-microservice-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/iam-jks-1.4.5.jks

dibymadhuri ojha
10 months ago
Reply to  Sumanth

I am aslo facing same isssue any solution please

Matteo
3 years ago

Hi mkyoung!

Is there a way to read from a classpath of an external library (included in my classpath obiously)