springboot打成war包找不到文件

项目在eclipse运行是可以的,但是打成war包到线上报错:

FileNotFoundException: class path resource [static/apiclient_cert.p12] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/****-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/apiclient_cert.p12

代码:

ClassPathResource classPathResource = new ClassPathResource("apiclient_cert.p12");

  到打的war包下BOOT-INF/classes!/static/apiclient_cert.p12是能找到该文件的,但是程序运行时却没找到。后来百度了一下,发现在线下运行时,是能到本地磁盘里找到该资源的。但是到线上该文件是存在于war包文件资源里,而不是真实存在于磁盘路径上。

    //1.通过getResourceAsStream()指定要加载的文件与当前类所在路径是一致的,从而获取到文件流
InputStream stream = getClass().getClassLoader().getResourceAsStream("static/apiclient_cert.p12"); File targetFile = new File("apiclient_cert.p12"); try {
//将读取到的类容存储到临时文件中,后面就可以用这个临时文件访问了   FileUtils.copyInputStreamToFile(stream, targetFile); }
catch (IOException e) { e.printStackTrace(); }

原文地址:https://www.cnblogs.com/ITyannic/p/9467777.html