之前使用读取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();
}
}