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 the Author

author image
mkyong
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

avatar