之前使用读取resources下的json文件,后来发现不通用,在这里做一些记录。
打成jar包之后,没有办法读取里面的路径。使用流的方式进行
一:实践
1.说明
使用了org.springframework.core.io.ClassPathResource
2.现在程序使用的方式
调用地方:
1 2 3 4 5 6 7 8 9 10 11 12 | public List<DspsInfo> parseDspInfoJson() throws IOException { String path = "dsp.json" ; String jsonStr = PropertiesUtils.getJsonStr(path); List<DspsInfo> dspsInfoList = JSON.parseObject(jsonStr, new TypeReference<List<DspsInfo>>() { }); if (!CollectionUtils.isEmpty(dspsInfoList)) { dspsInfoList.forEach(dspsInfo -> { dspsInfo.setDTime(DateUtils.format(DateUtils.DATE_FORMAT_SECOND)); }); } return dspsInfoList; } |
读取逻辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import java.io.*; public class PropertiesUtils { public static String getJsonStr(String fileName) throws IOException { Resource resource = new ClassPathResource(fileName); InputStream is = resource.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String data = null ; StringBuilder builder = new StringBuilder(); while ((data = br.readLine()) != null ) { builder.append(data); } br.close(); isr.close(); is.close(); return builder.toString(); } } |
二:另一种方式
1.说明
结合spring注解,使用org.springframework.core.io.ResourceLoader;类的注解
2.程序
需要使用注解,程序在测试类中测试,需要添加classpath
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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; /** * ceshi */ @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(); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~