尝试了很多读取resource资源文件的方式,很多读取不到或者是读取配置文件的形式。
以下两种方式,方式一用于通过启动jar方式时读取,方式二是本地IDE启动时读取。
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
private static InputStream getResource(String xmlPath) {
try {
// 方式一读取,读取不到使用方式二
ClassPathResource resource = new ClassPathResource(xmlPath);
if (resource.exists()) {
return resource.getInputStream();
}
// 方式二读取,本地启动时读取
File file = ResourceUtils.getFile(xmlPath);
if (file.exists()) {
return new FileInputStream(file);
}
log.error("资源不存在,地址:" + xmlPath);
throw new BusinessException("资源不存在,地址:" + xmlPath);
} catch (IOException e) {
log.error("读取文件异常", e);
throw new BusinessException("读取文件异常,地址:" + xmlPath);
}
}



