Spring Read file from resources folder
By:Roy.LiuLast updated:2019-08-11
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
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");
From:一号门
COMMENTS