1、起因
将支付验正证书信息放在项目的resources资源文件下在本地通过
this.getClass().getResource("/").getPath()
可以正常读取证书信息,但是打包部署到linux服务器上时报java.io.FileNotFoundException
2、解决方法
使用applicationHome.getSource().getParentFile().toString();读取jar包中的文件流。具体代码如下:
public class CopyCertFile {
/**
* (解决linux系统上找不到证书文件问题)
* @param certPath
*/
public void copyCertFile(String certPath){
ApplicationHome applicationHome = new ApplicationHome(CopyCertFile.class);
//项目打包成jar包所在的根路径
String rootPath = applicationHome.getSource().getParentFile().toString();
String configFilePath = rootPath + certPath;
File configFile = new File(configFilePath);
if (!configFile.exists()) {
try {
//获取类路径下的指定文件流
InputStream in = this.getClass().getClassLoader().getResourceAsStream(certPath);
FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "证书文件找不到"), configFile);
} catch (IOException e) {
throw new IllegalArgumentException("保存文件证书失败->" + e.getMessage());
}
}
}
}