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:一号门
RELATED ARTICLES
- Spring boot 读取配置文件properties
- Spring boot 非web版(jar)入门配置程序-maven工程源码
- Spring4 + Quartz Scheduler 执行定时任务例子
- Spring mvc @PathVariable 得到的参数包含点号的处理办法
- 同时绑定 spring validator和hibernate validator作为校验
- Spring security method 方法级别的权限控制
- spring mvc controller间跳转 重定向 传参数的几种方式
- 利用annotation与AOP对任何方法实现拦截. 附源码下载
- 在spring中常被忽视的注解 @Primary
- 在servlet中用spring @Autowire 注入.
- Spring MVC 返回 xml 数据的配置方法
- 给同事做的Spring data JPA培训的教程及例子
- 给新同事做的spring mvc 培训教程及例子
- mybatis spring 集成 bootstrap 例子一个
- spring3 restful 服务迁移到 spring4需要注意的事项
- maven 工程启动找不到 Spring ContextLoaderListener 的解决办法
- spring mvc jackson 防止XSS 注入方法
- spring mvc inteceptor 拦截器实现计算controller 的执行时间
- spring security JDBC 数据库实现,5个表, 例子下载
- spring security 教程入门
COMMENTS