SpringBoot读取resources下的文件以及resources的资源路径
1.这种可以 但是在容器中获取不到(以下几种都可以只要不在容器)。
InputStream inputStream = this.getClass().getResourceAsStream("/static/imgs/aha.png");
Properties pps = new Properties(); File file = ResourceUtils.getFile("classpath:defult.properties"); pps.load(new FileReader(file));
Properties pps = new Properties(); InputStream stream = getClass() .getClassLoader() .getResourceAsStream("defult.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); pps.load(br);
//获取resources下文件夹路径 File directory = new File("../项目名/src/main/resources"); String reportPath = directory.getCanonicalPath(); String resource =reportPath+"\\files\\**"; //resource就是所需要的路径 eg: resource="D:\项目名\src\main\resources\files\****"
2.容器和服务器中都可以获取
import cn.hutool.core.io.resource.ResourceUtil; //用hutool工具包的ResourceUtil public static InputStream getTemplateXslmAsStream() throws IOException { return ResourceUtil.getStream("templates/gojob/excel/job_define.xlsm"); }
package com.bme.shed.service; import com.bme.shed.BmeShedSimulateServiceApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringRunner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @RunWith(SpringRunner.class) @SpringBootTest public class RcvCentInfoParse { @javax.annotation.Resource ResourceLoader resourceLoader; @Test public void testReaderFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:dsp.json"); InputStream is = resource.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String data = null; while((data = br.readLine()) != null) { System.out.println(data); } br.close(); isr.close(); is.close(); } }
吾乃代码搬运工,侵联删
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)