日常开发中,我们经常需要读取项目resources目录下的文件,比如说Excel模板,或者是lua脚本。这时候我们就需要在代码中读取resources文件的内容。下面列举下springboot中的三种文件加载方法。
- @Test
- public void getResourceTest() throws IOException {
- ClassPathResource classPathResource = new ClassPathResource("测试.txt");
- InputStream in = classPathResource.getInputStream();
- //这里直接利用commons-io包将流转换成string
- System.out.println(IOUtils.toString(in));
- }
- @Test
- public void getResourceTest() throws IOException {
- InputStream in = this.getClass().getClassLoader().getResourceAsStream("测试.txt");
- System.out.println(IOUtils.toString(in));
- }
- @Test
- public void getResourceTest() throws IOException {
- InputStream in = this.getClass().getResourceAsStream("/test.txt");
- getFileContent(in);
- }
上面所谓的三种写法,其实本质上思路都是一样的,方法一中的classPathResource.getInputStream(),可以看下getInputStream()方法源码,其实就是一样的
- public InputStream getInputStream() throws IOException {
- InputStream is;
- if (this.clazz != null) {
- //这里其实就是方法二
- is = this.clazz.getResourceAsStream(this.path);
- } else if (this.classLoader != null) {
- //这里其实就是方法三
- is = this.classLoader.getResourceAsStream(this.path);
- } else {
- is = ClassLoader.getSystemResourceAsStream(this.path);
- }
-
- if (is == null) {
- throw new FileNotFoundException(this.getDescription() + " cannot be opened because it does not exist");
- } else {
- return is;
- }
- }
方法三中的this.getClass().getResourceAsStream,其实到getResourceAsStream方法里面去看
- public InputStream getResourceAsStream(String name) {
- name = resolveName(name);
- ClassLoader cl = getClassLoader0();
- if (cl==null) {
- // A system class.
- return ClassLoader.getSystemResourceAsStream(name);
- }
- //这里其实和方法二是一样
- return cl.getResourceAsStream(name);
- }
所以说其实加载resources中的文件原理和springboot加载class文件原理一样。