借助Spring的Resource去读取资源文件

在阅读Spring源码的过程中,我们可以看到,Spring的配置文件读取是通过ClassPathResource进行封装的,在日常的开发工作中,资源文件的加载也是经常用到的,可以直接使用Spring提供的类。而且可以使用该类支持的其他功能。

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.io.InputStream;
/**
 * @author yuyufeng
 * @date 2018/6/12.
 */
public class App {
    public static void main(String[] args) throws IOException {
//        Class.getResource("") 获取的是相对于当前类的相对路径
//        Class.getResource("/")    获取的是classpath的根路径
//        ClassLoader.getResource("")   获取的是classpath的根路径
        Resource resource = new ClassPathResource("/hello.txt");
        InputStream is = resource.getInputStream();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_18860653/article/details/80923416
今日推荐