各种情况下读取项目文件夹下文件
一、工具类
public final class ResourceLoaderUtil {
private static final Logger log = LoggerFactory.getLogger(ResourceLoaderUtil.class);
/**
* 扫描资源文件路径
*/
private static final List<String> SCAN_LOCATIONS = Collections.unmodifiableList(Arrays.asList("file:cfg/", "file:./config/", "file:./"
, "classpath:/config/", "classpath:/"));
private static final ResourceLoader LOADER = new DefaultResourceLoader();
/**
* load resource of data.json
*
* @return
*/
public static Resource loadResource(String resourcePath) {
Resource resource = null;
for (String loc : SCAN_LOCATIONS) {
resource = ResourceLoaderUtil.LOADER.getResource(loc.concat(resourcePath));
if (resource.exists()) {
break;
} else {
resource = null;
}
}
if (resource == null) {
log.warn(" cannot load resource [{}]", resourcePath);
return null;
}
return resource;
}
}
二、使用
private static final String CONFIG_FILE = "historydata.json";
org.springframework.core.io.Resource resource = ResourceLoaderUtil.loadResource(CONFIG_FILE);
InputStream inputStream = resource.getInputStream();
InputStreamReader isReader= new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isReader);
String readLine;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
br.close();
String json = sb.toString();