在springboot项目resource下增加了一个配置文件,在本地测试通过以下列子都可以正常读取
ResourceUtils.getFile("classpath:/ca/enterprise.xx");
在部署到测试环境的打成jar部署的docker容器里,报了一个错读取不到jar包中的文件。各种读取方法的尝试,最终使用以下方式可以正常读取
/**
* 在jar包中读取对象
* @param enterpriseCerFilePath
* @return
* @throws IOException
*/
public String getSignCertByJarFile(String enterpriseCerFilePath) throws IOException
{
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try{
InputStream stream = getClass().getClassLoader().getResourceAsStream(enterpriseCerFilePath);
inputStreamReader = new InputStreamReader(stream); // 建立一个输入流对象reader
bufferedReader = new BufferedReader(inputStreamReader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
StringBuffer stringBuffer = new StringBuffer();
String line= bufferedReader.readLine().trim();
while (line != null) {
stringBuffer.append(line);
line = bufferedReader.readLine(); // 一次读入一行数据
}
return stringBuffer.toString();
}catch(IOException ioe){
ioe.printStackTrace();
throw ioe;
}finally{
if(null != bufferedReader) bufferedReader.close();
if(null != inputStreamReader) inputStreamReader.close();
if(null != fileInputStream) fileInputStream.close();
}
}
public String getSignCertByJarFile2(String enterpriseCerFilePath) throws IOException
{
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try{
ClassPathResource ClassPathResource = new ClassPathResource(enterpriseCerFilePath);
bufferedReader = new BufferedReader(new InputStreamReader(ClassPathResource.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line= bufferedReader.readLine().trim();
while (line != null) {
stringBuffer.append(line);
line = bufferedReader.readLine(); // 一次读入一行数据
}
return stringBuffer.toString();
}catch(IOException ioe){
ioe.printStackTrace();
throw ioe;
}finally{
if(null != bufferedReader) bufferedReader.close();
if(null != inputStreamReader) inputStreamReader.close();
if(null != fileInputStream) fileInputStream.close();
}
}
先记录下解决方案,后续在写具体原因,jar包中的文件读取和在应用中的文件读取不太一样