标签:springboot springframework io org close import new resources 读取
之前使用读取resources下的json文件,后来发现不通用,在这里做一些记录。
打成jar包之后,没有办法读取里面的路径。使用流的方式进行
一:实践
1.说明
使用了org.springframework.core.io.ClassPathResource
2.现在程序使用的方式
调用地方:
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; }
读取逻辑:
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
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(); } }
标签:springboot,springframework,io,org,close,import,new,resources,读取 来源: https://www.cnblogs.com/juncaoit/p/16410801.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。